#!/bin/sh

format=none

if [ "$1" = "-gw" ]; then
  format=gw
  shift
fi

if [ "$1" = "-gml" ]; then
  format=gml
  shift
fi

if [ "$1" = "" ]; then
  echo ""
  echo "usage: run_agd [ -gw | -gml ]  <alg>  [ifile] [ofile]"
  echo ""
  echo "       runs AGD algorithm \"alg\" on the graph read from \"ifile\" "
  echo "       writes result to \"ofile\". If \"ofile\" or \"ifile\" are"
  echo "       missing std output and input are used, respectively."
  echo "       If the optional format switch (-gw or -gml) is omitted"
  echo "       the graph format is determined by the suffix of \"ifile\"." 
  echo ""
  exit
fi


if [ $format = none ]; then
  if [ "$2" = "`basename $2 .gml`.gml" ]; then
    format=gml
  else
    format=gw
  fi
fi


rm -f run_agd.log

if [ ! -f agd_options ]; then
  agd_server list agd_options > run_agd.log 2>&1
fi


alg=$1


if grep -q "function \"$alg" agd_options; then
  ffound=1
else
  echo ""
  echo "run_agd: $alg not in function list"
  echo ""
  grep function agd_options | grep -v "\[" | sed s/function//
  exit
fi
  

if [ "$2" = "" ]; then
   cat - > agd_infile
else
   if [ -f $2 ]; then
      cp $2 agd_infile
   else
     echo ""
     echo "run_agd: cannot open $2."
     echo ""
     exit
   fi
fi


if agd_server $alg agd_infile agd_options $format $format >> run_agd.log 2>&1
then
  err=0
else
  err=1
  cat agd_infile >> agd_run.log
fi;


if [ "$3" = "" -o $err = 1 ]; then
   cat agd_infile
else
   mv agd_infile $3
fi


rm -f agd_infile


