#!/bin/sh
#
# edt version 1.03 as of 26JUN95
#
# This is a shell wrapper to switch to edt-keymappings whenever
# emacs is to be called in edt-emulation mode. There is only a
# change in keytables if you call this from the console, since
# VT220/VT320 has its own feature to switch key bindings.
#
# 

OUTPUT=0				# no output option

while getopts o: option 2> /dev/null	# do we have an option?
do
  case "$option" in
    o) OUTPUT=1				# keep it in mind
       outfile=$OPTARG			# this is where we write to
  esac
done
shift `expr $OPTIND - 1`		# get rid of options

if [ "$#" -ne 1 ]			# too few arguments
then
  echo usage: edt [ -o outfile ] infile
  exit 1
fi


if [ "$OUTPUT" -eq 1 ]			# we read 1 file and write another
then
  targetdir=`dirname $outfile`		# can we write the output?
  if [ "targetdir" = "" ]		# output is to actual path
  then
    targetdir="."
  fi

  infile=$1				# the last argument is our input

  if [ ! -w "$targetdir" -o ! -x "$targetdir" ]  # this is not possible
  then
    echo edt: can\'t create output file $outfile
    exit 2
  elif [ ! -r "$infile" ]			# can we read the input file?
  then
    echo edt: can\'t read input file $infile
    exit 3
  else
    if [ -f $outfile ]			# does output file exist?
    then
      mv -f $outfile ${outfile}~	# if so, then move it away
      MOVED=1				# keep this in mind
    else
      MOVED=0				# we've not moved it
    fi

    cp $HOME/.emacs.edt $HOME/.emacs	# activate edt behaviour

    # this is for reading the input file into the output file's buffer
    echo "(defun include-auto-include-files ()" >> $HOME/.emacs
    echo "             (insert-file \"$infile\"))" >> $HOME/.emacs
    echo  >> $HOME/.emacs
    echo "(setq find-file-not-found-hooks '(include-auto-include-files))" \
		>> $HOME/.emacs
  fi
else
  cp $HOME/.emacs.edt $HOME/.emacs	# activate edt behaviour
  outfile=$1				# argument is file to edit
fi

# Now we call our favorite editor:
emacs $outfile				# edit file

if [ "$OUTPUT" = "1" ]			# remove the rest
then
  if [ ! -f $outfile -a "$MOVED" -eq 1 ]	# we left without writing
  then
    mv $outfile~ ${outfile}		# so restore the original file
  fi
fi

cp $HOME/.emacs.org $HOME/.emacs	# reset to default behaviour

