#!/bin/sh
#
# "open"	K. J. Turner	13/12/95
#
# This script starts applications for the files given as parameters.
# If a file extension is not given, a file with an extension is used
# if it is unique. If the file extension is not unique, the first one
# alphabetically is proposed. Extensions ending with "~" or ".backup" are
# assumed to be backup files and are ignored. Similarly, files with a ".lck"
# extension are taken as lock files and ignored.

# The script takes the same "-a" (application) and "-p" (print) flags as the
# usual "open" command. The directory for this script must appear ahead of
# the directory for the standard "open" (i.e. "/usr/bin/open") in $PATH.

flags=""
files=""
prog=`basename $0`

trap 'echo; echo $prog: abandoned; echo; exit 1' 2 3 15

if [ $# -eq 0 ]
  then
    echo "usage: $prog [-a app] [-p] files"
    exit 0
fi

while [ $# -gt 0 ]
  do
    case $1 in
      -a)
        flags="$flags -a $2"; shift 2;;
      -a*)
        flags="$flags -a `expr $1 : '-a\(.*\)'`"; shift;;
      -p)
        flags="$flags -p"; shift;;
      -*)
        echo "$prog: unknown flag $1"; shift;;
      *)
        file="`basename $1`"		# strip off leading directories
        file=`expr "Z$file" : 'Z\(.*\)\..*'`
	if [ "$file" = "" ]
	  then				# filename has no dot
	    names=""
	    count=0
	    for name in $1 $1.*		# consider all extensions
	      do
	        if [ "$name" != "$1.*" -a -r "$name" ]
		  then
		    ext="`expr Z$name : 'Z.*\(~\)'`"
		    if [ "$ext" = "" ]
		      then ext="`expr Z$name : 'Z.*\.\([^.]*\)'`"
		    fi
		    if [ "$ext" != "backup" -a "$ext" != "lck" \
		         -a "$ext" != "~" ]
		      then		# ignore backup and lock files
			names="$names $name"
			count=`expr $count + 1`
		    fi
		fi
	      done
	    if [ $count -eq 1 ]
	      then
	        files="$files $names"
              else
	        if [ $count -gt 1 ]
		  then
		    for name in $names
		      do
			echo -n "$prog: ambiguous name, use $name (y/n)? "
			read ans
			if [ "$ans" != "n" -a "$ans" != "N" ]
			  then
			    files="$files $name"
			    shift
			    continue 2
			fi
		      done
		fi
	    fi
	    shift
	  else				# filename has dot
	    name="$1"
	    ext="`expr Z$name : 'Z.*\.\([^.]*[^~]\)$'`"
	    if [ "$ext" = "" ]		# extension ends with ~, so set this
	      then ext="~"
	    fi
	    if [ "$ext" != "backup" -a "$ext" != "lck" -a "$ext" != "~" ]
	      then			# ignore backup and lock files
		files="$files $name"
	    fi
	    shift
	fi;;
    esac
  done

if [ "$files" != "" ]
  then /usr/bin/open $flags $files
  else echo "$prog: no files to open!"
fi

exit 0
