#!/bin/sh

set -e

case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
  *c*,-n*) ECHO_N= ECHO_C='
' ECHO_T='      ' ;;
  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
esac

${MAKE:-make} histauto
MKDIR=${MKDIR:-mkdir}

##### some definitions #####

history_to_unknown='s/:history = ".*>/:history = "unknown unknown>/'
#date_to_unknown='s/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9][+-][0-9][0-9]:[0-9][0-9]/unknown/'
delete_orig='s/\.orig//' 

files="tmp.nc tmp1.nc tmp2_t0.nc tmp2_t120.nc tmp2_t240.nc tmp3.nc"
origfiles="tmp.orig.nc tmp1.orig.nc tmp2_t0.orig.nc tmp2_t120.orig.nc tmp2_t240.orig.nc tmp3.orig.nc"

test -d xhistauto || $MKDIR xhistauto

##### make CDL file from Original data by ncdump #####
cd xhistauto
for file in $origfiles
do
   ncdump $file | sed -e "$history_to_unknown" -e $delete_orig > $file.cdl
done
cd ..

##### Execute histauto #####
for file in $files
do
   test ! -f xhistcopy/$file || rm -f xhistcopy/$file
done
./histauto > xdifs.log 2>&1

##### Make CDL file #####

cd xhistauto
for file in $files
do
    ncdump $file | sed "$history_to_unknown" > $file.cdl
done

##### test ######

for file in $files
do
   echo $ECHO_N "testing $file ..." $ECHO_C
   origfile=`echo $file | sed 's/nc$/orig.nc/'`
   diff $file.cdl $origfile.cdl
   echo "okay"
done

rm -f ../xdifs.log *.cdl $files

exit 0
