#!/bin/sh
#+
# 
#  USAGE:     cmc4bernese <ocean.cmc> [<destination>]
# 
#  PURPOSE:   Produces the BLQ header part with CMC coefficients
#             as Bernese software likes it.
# 
#             If ~/www/CMC/<ocean.cmc> exists, script does
#             cd ~/www/CMC/
#             If $WPOL/CMC/<ocean.cmc> exists, script does
#             cd $WPOL/CMC/<ocean.cmc>
#             else <ocean-cmc> must specify the path.
# 
#  ARGUMENT:
# 
#    <ocean.cmc>    - e.g. HAMTIDE.cmc
# 
#    <destination>  - can be a directory. In this case, output is to
#                     <destination>/`basename $1`
#                     E.g. cmc4bernese HAMTIDE.cmc ../BLQ-CMC
# 
#                     alternatively a file, which will be over-written
#                     if it already exists.
# 
#                     Default: STDOUT
# 
#  COMMANDLINE USE
# 
#_
if [ x$1 = x-h ]; then
   helptext + _ $0
   exit
fi

if [ -r ~/www/CMC/$1 ]; then
   cd ~/www/CMC/
   bn=$1
elif [ -r $WPOL/CMC/$1 ]; then
   cd WPOL/CMC/$1 
   bn=$1
else
   bn=`basename $1`
fi
if [ ! -r $bn -a ! -r $1 ]; then
   echo "You are in "`pwd`
   echo "File $bn ( $1 ) don't exist. Try one of those:"
   sugg=`sb $bn 1,4`
   ls $sugg*.cmc
   exit
fi

if [ x$2 = x ]; then 
  awk 'BEGIN{print "$$ CMC start : center of mass coefficient file content"} \
       {if (NR==1){print "$$ CMC format:",$0}else{print "$$ CMC frequ :",$0}} \
       END{print "$$ CMC end   :"}' $1
  echo " "
  echo "You are in "`pwd`
  echo "Suggestion: Redirect to `pwd`/../BLQ-CMC/$bn" 
elif [ -d $2 ]; then
    if [ -r $2/$bn ]; then
       echo -n "$2/$bn exists - over-write (y/n) "
       read -r ans
       if [ x$ans = xn -o x$ans = xN ]; then
          exit
       fi
    fi
    awk 'BEGIN{print "$$ CMC start : center of mass coefficient file content"} \
       {if (NR==1){print "$$ CMC format:",$0}else{print "$$ CMC frequ :",$0}} \
       END{print "$$ CMC end   :"}' $1 > $2/$bn
    echo "You are in "`pwd`
    echo "Output to $2/$bn"
else 
    if [ -r $2 ]; then
       echo -n "$2 exists - over-write (y/n) "
       read -r ans
       if [ x$ans = xn -o x$ans = xN ]; then
          exit
       fi
    fi 
    awk 'BEGIN{print "$$ CMC start : center of mass coefficient file content"} \
       {if (NR==1){print "$$ CMC format:",$0}else{print "$$ CMC frequ :",$0}} \
       END{print "$$ CMC end   :"}' $1 > $2
fi
exit

