#!/bin/sh

# nedits: calls neditc with a server name built from the current directory.
# if first parameter is -f, then use the path part of that parameter as the
# current directory
set -f

cd `pwd -P`

fil=""
if [ "x$1" = "x-f" ] && [ "x$2" != "x" ]
then
  shift
  dir=`echo "$1" | sed -e "s:/[^/]*$::"`
  fil=`echo "$1" | sed -e "s:.*/::"`
fi

if [ "x$dir" != "x" ]
then
  cd $dir
fi

tdir="$PWD"
tagpath=""
while [ "$tdir" != / ]; do
  if [ -f "$tdir"/tags ] || [ -f "$tdir"/TAGS ]; then
    [ -f "$tdir"/tags ] && tagpath="$tdir"/tags || tagpath="$tdir"/TAGS
    break
  fi
  [ "$tdir" = "$HOME" ] && break
  tdir=`dirname "$tdir"`
done
[ -n "$tagpath" ] && tagpath="-xrm 'nedit.tagFile: $tagpath'"

tab=`echo : | tr : "\t"`
s=`pwd | sed -e "s:/:_D_:g" \
             -e "s:\\.:_d_:g" \
             -e "s/:/_c_/g" \
             -e "s/-/_m_/g" \
             -e "s/[^A-Za-z0-9 $tab]/_/g"`
s="-svrname $s"

i=''
if [ -r ./nedit.def ]; then
  i='-import ./nedit.def'
fi

ask=-noask
# setsid nc -noask -xrm 'nc.autoStart: True' \
#                  -xrm "nc.serverCommand: nedit $i" $s "$@" &
# LC_CTYPE=en_GB.iso88591 LC_COLLATE=C \
LANG=C
LC_CTYPE=C
export LANG LC_CTYPE

#if [ "x$fil" != "x" ]
#then
#  shift
#  setsid nc -noask -xrm 'nc.autoStart: True' $s "$fil" "$@" &
#else
#  setsid nc -noask -xrm 'nc.autoStart: True' $s "$@" &
#fi

NEDITS_NC_CMD="nc -noask -xrm 'nc.autoStart: True' $tagpath $s"
if [ "x$fil" != "x" ]
then
  shift
  # NEDITS_NC_CMD="$NEDITS_NC_CMD '$fil'"
  NEDITS_NC_CMD="$NEDITS_NC_CMD $escfil"
fi
for f in "$@"; do
  # NEDITS_NC_CMD="$NEDITS_NC_CMD '$f'"
  escfil=`echo "$f" | sed -e 's/[][{}|*?\\|&;()<>'" $tab\'\""'\$#]/\\\\&/g'`
  NEDITS_NC_CMD="$NEDITS_NC_CMD $escfil"
done
export NEDITS_NC_CMD
# tty -s && echo "$NEDITS_NC_CMD"
exec sh -c "setsid $NEDITS_NC_CMD &"
