#! /bin/bash 
# Check for valid arguments: runid tok year
# 1st argument must be a filename
# Arguments are ordered and written into filename 
# 12/17/03 C.Ludescher-Furth
#
PGR="tr_ckargs"

tmpfile=$1
shift

allargs=($*)

#Test if tr_checkid.pl is in $PATH
type tr_checkid.pl > /dev/null 2>&1
if [ $? != 0 ]; then
   echo "${PGR}: -E- can not find tr_checkid.pl "
   exit 0
fi
#Test if can write into #tmpfile
touch $tmpfile > /dev/null 2>&1
if [ $? = 1 ]; then
      echo "${PGR}: -E- $tmpfile is not writable"
      exit 0
fi
rm -f $tmpfile

# loop through arguments
let n=0
let k=-1

for arg
do
  test=`echo $1 |tr '[a-z]', '[A-Z]'`
  let k=k+1
  shift

#Check if year = 2 digits
  tyy=`echo $test | sed 's/[0-9]//g'`
  if [ "${year}###" == "###" -a ${#test} -eq 2 -a -z "$tyy" ]; then
     year=$test
     let n=n+1
#Check if runid
  elif [ -z "$runid" -a `tr_checkid.pl $test` == "valid" ]; then
     runid=$test
     let n=n+1
  else
#Check if tok.yy
    if [ -z "$tok" -a $test != ${test##*.} ]; then
      ttok=${test%.*}
      yy=${test##*.}
      tyy=`echo ${test##*.} | sed 's/[0-9]//g'`
#      yy=`echo $test | sed 's/[a-z A-Z]*\.//'`
      if [  ${#yy} -eq 2 -a -z "$tyy" ]; then
        year=${test##*.}
        let n=n+1
      else
        echo "${PGR}: -E- $test not a valid tok.yy"
        exit 0 
      fi
    elif [ -z "$tok" -a ${#test} -ge 3 -a ${#test} -le 4 ]; then
      ttok=$test
    else
      echo "${PGR}: -E- $test is an invalid argument"
      exit 0
    fi
#Check if Tokamak
    tok_valid $ttok silent
    tvalid=$?
    if [ $tvalid = 1 ]; then
      tok=$ttok
      let n=n+1
    else
      tok_valid $ttok
      error=y
    fi
  fi
done


if [ -n "$error" ]; then
    echo "${PGR}: -E- invalid arguments: ${allargs[@]}"
    exit 0
fi

echo "$runid:$tok:$year" > $tmpfile
if [ $? -ne 0 ]; then
    echo "${PGR}: -E- can not create temp file $tmpfile"
    exit 0
fi
exit 1
