#!/bin/csh -f
# Generate snapshot velocity field using all data
#
if( $#argv == 0 ) then
    echo "sh_snapvel Usage:"
    echo "sh_snapvel -cen <CEN> -cmd <tsfit command file>"
    echo "Options:"
    echo "-cen <CEN>  Processing to used NMT/CWU/COM (default)"
    echo "-cmd <tsfit command file> (../tables/tsfit.cmd)
    echo " "
    exit
endif
# 
#
# Defaults
set cen = 'COM'
set cmd = '../tables/tsfit.cmd'
#

foreach a ($argv)
  switch($a)

#   Center
    case -ce*:
       set cen = $argv[2]
       set nam = $cen
       if( $nam == 'COM' ) set nam = "PBO"
       breaksw

#   Command file name
    case -cm*:
       set cmd = $argv[2]

  endsw
  shift
end

# Generate output file: Get last day of data to be used
pd ../$cen
   set tsdir = `echo $cen | awk '{printf("ts_%s",tolower($1))}'`
   set lastpos = `ls -tr $tsdir/*final_nam08.pos | tail -1`
   set rframe = "nam08" 
   set endd = `grep "Last Epoch" $lastpos | awk '{print substr($4,3)}'`
   set sumroot = `echo $nam $rframe $endd | awk '{printf("%s_%s_%s",tolower($1),$2,$3)}'`
   if ( ! -e SNAPSHOT ) mkdir SNAPSHOT 
#
#  Run tsfit
   tsfit $cmd ${sumroot}.sum $tsdir/*final_nam08.pos
#
#  Now create the snapshot velocity field file.
   echo "Creating ${sumroot}.snpvel"
   echo "PBO SNAPSHOT Velocity Field" >! ${sumroot}.snpvel
   echo "Format Version         : 1.00" >> ${sumroot}.snpvel
   set ts = `date +"%Y%m%d%H%M%S"`
   echo "Release Date           : $ts" >>  ${sumroot}.snpvel
   echo "Reference Frame        : NOAM_I08" >>  ${sumroot}.snpvel
   echo "Analysis Center        : $nam " >>  ${sumroot}.snpvel
   echo "TSFIT Command File     : $cmd " >>  ${sumroot}.snpvel
   echo "#START Commands " >>  ${sumroot}.snpvel
   grep '^# ' ${sumroot}.vel >>  ${sumroot}.snpvel
   echo "#END Commands " >>  ${sumroot}.snpvel
   echo ".   Long      Lat       Evel     Nvel    E +-     N +-      Rne      Hvel     H +-   Site" >>  ${sumroot}.snpvel
   echo ".   deg       deg      mm/yr    mm/yr    mm/yr    mm/yr             mm/yr    mm/yr" >>  ${sumroot}.snpvel
   grep '^ ' ${sumroot}.vel | awk '{printf(" %9.5f %8.5f %8.2f %8.2f %8.2f %8.2f  %7.3f %8.2f %8.2f   %s\n",$1,$2,$3,$4, $7,$8,$9,$10,$12,$13)}' >>   ${sumroot}.snpvel





