#!/bin/bash
# could be improved a lot.....

#
# Input:  SNAP file created with DRUDG from the schedule for your station
#
# Output: The 'recexpt_[stationID]-tsunami' file for recording the experiment 
#         via real-time Tsunami client
#         You may need to edit 'recpass-tsunami' for correct server name and 
#          data rate settings.
#

STATION=Mh

if [ "$1" == "" ]; then
  SNP=euro85on.snp
else
  SNP=$1
fi

# get scan names, convert "," to space
sed -n -e '/scan_name=/s/scan_name=//p' euro85on.snp | sed -n -e 's/,/ /gp' > scans

# get start times
sed -n -e '/preob/,/!/p' $SNP | grep ! | sed -n -e 's/[!.]/ /gp' > starttimes

# merge the two files
I=1
LC=`wc -l scans | awk '{print $1}'`
rm -f merged
while [ $I -le $LC ]
do
   SCAN_CURR=`tail +$I scans | head -1`
   TIME_CURR=`tail +$I starttimes | head -1`
   #echo " sc=${SCAN_CURR} tc=${TIME_CURR} "
   echo "${SCAN_CURR} ${TIME_CURR}" >> merged
   I=$(($I+1))
done

# create recexpt
cat recexpt-tsunami.head > recexpt_$STATION-tsunami
cat merged | while read scan expt dur1 dur2 year day clock; do 

   datestr=`date -d "jan 0 ${year} + ${day} days" +"%Y-%m-%d"` 
   
   # debug:
   #   echo "scan:${scan} expt:${expt} duration:${dur1}s/${dur2}s year:${year} day:${day} time:${clock}   -- ${datestr}T${clock}"
   
   # scan03_2006-12-19T11:15:00  300
   # debug
   echo "   ${scan}_${datestr}T${clock} ${dur1}"
   echo "   ${scan}_${datestr}T${clock} ${dur1}"  >> recexpt_$STATION-tsunami
done
cat recexpt-tsunami.tail >> recexpt_$STATION-tsunami


