#!/bin/sh

function usage()
{
   echo
   echo "Usage: $0 starg|tpoint yyyy mm"
   echo
   echo "   starg|tpoint  which kind of file you are going to join."
   echo "   yyyy          year you want to join in four digit notation."
   echo "   mm            month you want to join in two digit notation."
   echo
}

if ! [ `echo $@ | wc -w` -eq 3 ]
then
  usage
  echo ERROR: Wrong number of commandline argument.
  echo
  exit
fi

if ! [ `echo $2 | wc -c` -eq 5 ]
then 
  usage
  echo ERROR: Year must have four digits.
  echo
  exit
fi

if [ `echo $3 | wc -c` -gt 3 ]
then 
  usage
  echo ERROR: Month must not exceed 2 digits.
  echo
  exit
fi

year=$2
month=`printf %02d $3`
type=$1

output=$1$year$month.txt

path=/magic/subsystemdata/drive/$year/$month

echo
echo Processing $path.

files=(`find $path -name $1_$year$month*.txt -printf %P\\\n`)

if [ ${#files[@]} -eq 0 ]
then
   echo WARNING: No $1 files found.
   echo
   exit
fi

#if [ -e $output ]
#then
#   echo 
#   echo File exists
#fi

rm -f $output

echo Writing $output.

head -n 3 $path/${files[0]} >> $output

for file in ${files[@]}
do
   echo Reading $file...
   echo >> $output
   echo -n "# " >> $output
   head -n 3 $path/$file | tail -n 1 | cut -d\  -f 4- >> $output
   tac $path/$file | head -n -3 | tac >> $output
done

echo Done.
echo
