#! /bin/sh

if [ $# -eq 0 ]; then
    echo ""
    echo "Error: SPADEDIT expects one or two arguments."
    exit
fi

DEFAULTEDITOR='less +$line $name'
if [ "$FRICASTERM" = "" ] ; then
    DEFAULTXEDITOR='xterm -e "less +$line $name"'
else
    DEFAULTXEDITOR='$FRICASTERM -e "less +$line $name"'
fi

if [ "$FRICASEDITOR" = "" ] ; then
    echo ""
    if [ ! -z "$SPADNUM" ] && [ -z "$DISPLAY" ] ; then
        echo "Error: environment variable FRICASEDITOR not set."
        echo "We are in server mode but have no X."
        echo "No default way to edit/view files."
        exit
     fi
     if [ -z "$DISPLAY" ] ; then
         echo "Warning: environment variable FRICASEDITOR not set."
         echo "Using 'less'."
         echo "Press space to continue, 'q' to quit."
         FRICASEDITOR=$DEFAULTEDITOR
     else
         echo "Warning: environment variable FRICASEDITOR not set."
         echo "Launching 'less' in an 'xterm'."
         echo "Press space to continue, 'q' to quit."
         FRICASEDITOR=$DEFAULTXEDITOR
     fi
fi

if [ $# -eq 1 ]; then
    name=$1
    line=1
    eval $FRICASEDITOR
else
    f=$(basename $1 .spad)
    h=$(grep -n "^)abb.* $f " $FRICAS/src/algebra/*.spad)
    name=${h%%:*}
    line1=${h#*:}
    line=${line1%:*}
    eval $FRICASEDITOR
fi
