#! /bin/tcsh -f
# Authors: Hartwig Harder, 2009
# Authors: Rolf Sander,    2009-2012

##############################################################################

if ( "$1" == "" ) then
  echo "xtxt2nc = convert textfile (*.txt) to netcdf (*.nc)"
  echo "usage:"
  echo "   xtxt2nc <myfile.txt>"
  echo "or:"
  echo "   xtxt2nc *.txt"
  exit
endif

foreach inputfile ($argv)
  echo;echo "working on $inputfile..."
  set jnlfile = $inputfile:r.jnl
  set ncfile  = $inputfile:r.nc
  # convert from DOS (CRLF) to UNIX format:
  tr -d '\r' < $inputfile > tmp.txt
  diff $inputfile tmp.txt > tmp.dif
  if ( -s tmp.dif != 0 ) then
    echo "Conversion of input file from DOS to UNIX file format was necessary"
    mv $inputfile $inputfile~
    mv tmp.txt $inputfile
  endif
  # generate and execute a ferret skript:
  gawk -f txt2nc.awk "$inputfile"
  ferret -batch -script "$jnlfile"
  # ferret renames all to uppercase. Revert this now:
  ncrename -v PRESS,press            $ncfile
  ncrename -v TEMP,temp              $ncfile
  # for coordinate variable TIME, also change name of dimension:
  ncrename -v TIME,time -d TIME,time $ncfile
  # cleanup temporary files:
  rm $inputfile:r.jnl $inputfile:r_*.dat tmp.*
  rm time_ax_dum.nc metafile.plt
end

exit
