#!/bin/bash


#check for leagal number of parameter 
if test "$#" -lt 2; then
    echo -e "Usage:\n\nxmgrbachtplot <outputfile.ps> [grace command line options] <datafiles>\n\n\nOptions:\n\nThe files <datafiles> may contain '#' prefixed grace options. All options used by grace in its .arg files are supported. Options for a specific set must start with 's*'.The Asterix '*' is automaticaly replaces by the set number derived from the position of the corresponding datafile in <datafiles>.\n\n\nExample:\n\nAn Example for the first lines of a datafile with the probably most usefull options is attached below.\n\n#xaxis label \"x-Achsen bezeichner 2\"\n#xaxis label char size 1.400000\n#xaxis ticklabel char size 1.400000\n#xaxis ticklabel offset spec\n#xaxis ticklabel offset 0.000000 , 0.020000\n#yaxis label \"y-Achsen bezeichner 2\"\n#yaxis label char size 1.400000\n#yaxis ticklabel char size 1.400000\n#yaxis ticklabel offset spec\n#yaxis ticklabel offset 0.000000 , 0.020000\n#view 0.200000, 0.200000, 1.200000, 0.900000\n#s* symbol 1\n#s* symbol size 0.5\n#s* symbol color 2\n#s* line color 2\n#s* line type 1 # none; 2 normal; 3 barchart\n#s* legend \"dataset test.dat\""
    exit 1
fi


#set output file
outfile=$1


#init output string
out='#autogenerated gracebat file\n'


#use first given file to set graph wide parameters
for datafile in ${*:2}; do
    if test -f "$datafile"; then
	break
    fi
done
if test ! -f "$datafile"; then
    echo "no data files given"
    exit 2
fi
out=$out`awk '/^#[^s*]/ { sub("#",""); print $0"\\\n"}' $datafile`'\n\n'


#read set-specific options from .dat files
counter=0
for datafile in ${*:2}; do
    #jump over all non file command line argumnts
    if test ! -f "$datafile"; then
	continue
    fi
    tmp=`awk '/^#s\*/ {sub("#s[*]","s*"); sub("#.*",""); print $0"\\\n"}' $datafile`'\n'
    out=$out`echo ${tmp//"s*"/"s"$counter}`
    let counter=$counter+1 
done

#add outoscale option
out=$out'autoscale\n'


#write output
echo -e $out
echo -e $out>batchfile


#run grace
#gracebat $* -batch batchfile -printfile $outfile
xmgrace $* -batch batchfile -printfile $outfile -hardcopy


exit 0
