#!/bin/sh
# Copyright (c) 2002-10 Peter Guntert. All rights reserved.

# Startup script
# Peter Guntert, 21-01-2002


# ------ Serial number -----

serial=

# ------ Program name -----

PROG=CYANA
prog=uplabel
exe=${prog}exe

# ------ Command line options ------

cmd="\$exefile"
options=c:St:xh

optind=1
usage=""
eval par=\$$optind
while true; do
  case $par in
  --) optind=`expr $optind + 1`; break;;
  -?*) option=`echo X$par | sed 's/^X-\(.\).*/\1/'`
       if [ `echo $options | sed 's/.*'$option'.*/+/'` != "+" ]; then
         echo "$0: -$option: unknown option"; usage=1
       elif [ `echo $options | sed 's/.*'$option':.*/+/'` = "+" ]; then
         optind=`expr $optind + 1`
         eval $option=\$$optind
       else
         eval $option=1
       fi
       par=`echo X$par | sed 's/^X-./-/'`
       if [ "$par" = "-" ]; then 
         optind=`expr $optind + 1`
	 eval par=\$$optind
       fi
       ;;
  *) break;;
  esac
done
shift `expr $optind - 1`

if [ "$h" ]; then usage=1; fi
if [ "$usage" ]; then
  echo "Usage: $prog -hctx parameters ..."					         
  echo  									         
  echo "       -h	     help"						         
  echo "       -c command    command to start program (must contain \$exefile)"          
  echo "       -S            run in safe mode, i.e. within one directory"				         
  echo "       -t system     explicit system type"				         
  echo "       -x	     display name of executable without executing it"	         
  exit 2
fi
if [ "$c" ]; then cmd="$c"; fi
sys=$t
mode=$x
safe=$S


# ------ Treat command line parameters ------

eval ${PROG}ARG='$*'
export ${PROG}ARG


# ------ Set library name ------ 

f=$0
if [ `echo $f | sed 's,^/.*,+,'` != "+" ]; then f=`which $0`; fi
odir=`pwd`
while [ "`ls -l $f | awk '{ print substr($1,1,1) }'`" = "l" ]; do
  l=`ls -l $f | awk '{ i = NF; print $i }'`
  cd `dirname $f`; cd `dirname $l`; l=`pwd`/`basename $l`
  f=$l
done
cd `dirname $f`
libdir=`pwd | sed 's,/src/'${prog}'$,,'`
cd "$odir"
eval ${PROG}LIB=$libdir
export ${PROG}LIB

if [ "$safe" ]; then 
  CYANAINIT=initsafe; export CYANAINIT
fi
if [ "$CYANASERIAL" ]; then serial=$CYANASERIAL; fi
CYANASERIAL=$serial; export CYANASERIAL


# ------ Start the program ------

if [ -d $libdir/src/$prog ]; then
  exe=$libdir/src/$prog/$exe
else
  exe=$libdir/$exe
fi
if [ "$sys" = "" ]; then
  sys=`$libdir/etc/identify`
  files="$exe.$sys* $exe.gfortran $exe.*"
else
  files=$exe.$sys
fi
for exefile in $files; do
  if [ -x $exefile ]; then
    if [ "$mode" ]; then
      echo $exefile; exit 0
    else
      if [ "`echo $cmd | grep -c '\$exefile'`" -gt 0 ]; then
        eval exec $cmd
      else
        eval exec $cmd $exefile
      fi
    fi
  fi
done
echo "No executable found in \"`dirname $exe`\"."
exit 1
