#! /bin/csh -f

if (! $?BACKUP_HOME) then
  set p=$0
  set pnam=$p
  set pnam=$pnam:t
  if ($pnam == $0) then
    foreach dir ($path)
      if (-x $dir/$pnam) then
	set p=$dir/$pnam
	break
      endif
    end
  endif
  if (`echo $p|cut -c1` != "/") then
    set p=`pwd`/$p
  endif

  set oldpath=$p

 restart_resolv:
  set newpath="$oldpath"_
  while ("$newpath" != "$oldpath")
    set newpath="$oldpath"

    set oldpath=`echo "$oldpath"|sed 's#/\./#/#g;s#/\.$##g;s#//*#/#g;s#^\./##g;s#^/\.\./#/#g'`

    if ("$oldpath" != '/') then
      set oldpath=`echo "$oldpath"|sed 's#/*$##g'`
    endif
  end

  if (`echo "$oldpath"|cut -c1` == "/") then
    set oldhead="/"`echo "$oldpath"|cut -c2-|sed 's#/.*$##g'`
    set oldtail=`echo "$oldpath"|cut -c2-|sed 's#^[^/]*/##'`
  else
    set oldhead=`echo "$oldpath"|sed 's#/.*$##g'`
    set oldtail=`echo "$oldpath"|sed 's#^[^/]*/##'`
  endif
  if ("$oldpath" == "$oldhead") set oldtail=""

  while (1)
    if ("$oldhead" == "") set oldhead="."
    if (! -f "$oldhead" && ! -d "$oldhead") then
      set newpath=""
      goto getout_1
    endif

    set linkchar=`ls -ld "$oldhead"|cut -c1`
    if ($linkchar == 'l') then
      set points_to=`ls -ld "$oldhead"|sed 's#^.*->[ 	]*##g'`

      if (`echo "$points_to"|cut -c1` == '/') then
        set newpath="$points_to"/"$oldtail"
      else
        set newpath=`dirname "$oldhead"`/"$points_to"/"$oldtail"
      endif

      set oldpath="$newpath"
      goto restart_resolv
    endif

    if ("$oldtail" == "") then
      set oldpath="$oldhead"
      break
    endif

    set oldhead="$oldhead"/`echo "$oldtail"|sed 's#/.*$##g'`
    if (`echo "$oldtail"|grep /|wc -l` < 1) then
      set oldtail=''
    else
      set oldtail=`echo "$oldtail"|sed 's#^[^/]*/##g'`
    endif
  end

  set newpath="$oldpath"_
  while ("$newpath" != "$oldpath")
    set newpath="$oldpath"

    set oldpath=`echo $oldpath|sed 's#[^/][^/]*/\.\./##g;s#[^/][^/]*/\.\.$##g;s#/\./#/#g;s#/\.$##g;s#//*#/#g;s#^\./##g;s#^/\.\./#/#g'`

    if ("$oldpath" != '/') then
      set oldpath=`echo "$oldpath"|sed 's#/*$##g'`
    endif
  end

 getout_1:

  set p="$newpath"
  set p=$p:h

  setenv BACKUP_HOME $p:h
endif


unalias ls
set WISH=""
foreach dir ($path)
  if (! -d $dir) then
    continue
  endif

  set progs=`ls $dir|egrep '^wish([0-9]+[.]?)*$'`
  foreach prog ($progs)
    if (-x $dir/$prog) then
      set WISH=$dir/$prog
      break
    endif
  end

  if ("$WISH" != "") then
    break
  endif
end

if ("$WISH" == "") then
  echo "Error: window shell wish not found. Exiting."
  exit 1
endif

$WISH << END_OF_INPUT

