#!/bin/ksh
set -x

idd=$(printf "%02d" $i)
Caldtg='/home/shian/Caldtg.ksh'
tmps=${uvdtg}
tmpe=${uvdtg}
while [ $tmps -le $tmpe ]
 do

dtg10=${tmps}
dtg_y4=`echo ${dtg10} | cut -c1-4`
dtg_m2=`echo ${dtg10} | cut -c5-6`
dtg_d2=`echo ${dtg10} | cut -c7-8`
dtg_h2=`echo ${dtg10} | cut -c9-10`
dtg=`echo ${dtg10} | cut -c5-6`

 NCL=/cluster/ncl-6.5.0/bin/ncl
 CDO=/cluster/gcc-4.8.5/tools/bin/cdo
 NCKS=/cluster/gcc-4.8.5/tools/bin/ncks


NWPDTGGLB_Pre=/data/public/HYCOM/shian/forecast/SSH/H
NWPWRK_Pre=/data/public/HYCOM/shian/forecast/SSH
MAINHYCOM1=${upth}
NWPBIN=/data/public/HYCOM/shian/forecast/SSH
#====== Main
  if [ ! -d ${NWPDTGGLB_Pre}/${dtg}/${dtg_y4} ]; then
    mkdir -p ${NWPDTGGLB_Pre}/${dtg}/${dtg_y4}
  fi
 
  export  HYCOMWRK=${NWPWRK_Pre}/h_work
  if [ ! -s ${HYCOMWRK} ]; then mkdir -p ${HYCOMWRK} ; fi
  cd ${HYCOMWRK}

#========= check TIMCOM IC data & make IC ===========
  if [ ! -f ${NWPDTGGLB_Pre}/${dtg}/${dtg_y4}/full_H_${dtg10}.nc ]; then
    doTIMICr=1
    echo "$doTIMICr"
  else
    echo "${NWPDTGGLB_Pre}/${dtg}/${dtg_y4}/full_H_${dtg10}.nc exit"
    doTIMICr=0
  fi

  doICfHYCOM=0
  if [[ ${doTIMICr} -eq 1 ]]; then
    #=========================
    # 1. Check HYCOM ic
    #=========================
    # if [ ${dtg_h2} -eq 00 ]; then
    #   hycomicdtg=`${NWPBIN}/Caldtg.ksh ${dtg10} -12`
    # fi
    # if [ ${dtg_h2} -eq 12 ]; then
    #   hycomicdtg=`${NWPBIN}/Caldtg.ksh ${dtg10} -24`
    # fi

        hycomu3z=${MAINHYCOM1}
  ls -l ${hycomu3z}
    if [ -s ${hycomu3z} ] ; then
        doICfHYCOM=1
    fi
  fi

  if [ ${doICfHYCOM} -eq 1 ]; then
    #=========================
    # 1. step1_SeparateVar.sh
    #=========================
    ${CDO} chname,surf_el,SSH ${hycomu3z} ${HYCOMWRK}/n_hycom_${dtg10}_u.nc

    TIMarea=( 'r' )
    for area in ${TIMarea[@]}
    do
      if [ ${area} == 'r' ]; then
        doIC=${doTIMICr}
        export TCOM_FILE=~/timcom_grid_op.nc
      fi
   
      echo area=${area} doIC=${doIC}
      if [[ ${doIC} -eq 1 ]]; then  
        #=========================
        #=========================
        rm -f ${HYCOMWRK}/remap_hycom_${dtg10}_*.nc
        rm -f ${HYCOMWRK}/remap*.log
        ${CDO} -O remapnn,~/tar_grid.nc ${HYCOMWRK}/n_hycom_${dtg10}_u.nc   ${HYCOMWRK}/remap_hycom_${dtg10}_u.nc   >${HYCOMWRK}/remapU.log &
        wait
  
        # 5. run full horizontal value
        #=========================
        fileUU=${HYCOMWRK}/remap_hycom_${dtg10}_u.nc
        rm -f ${HYCOMWRK}/sfill*.log
        ${CDO} setmisstonn ${fileUU} nn_remap_hycom_${dtg10}_u.nc   >${HYCOMWRK}/sfillU.log &
        wait

        mv nn_remap_hycom_${dtg10}_u.nc ${NWPDTGGLB_Pre}/${dtg}/${dtg_y4}/full_H_${dtg10}.nc
        rm -f ${HYCOMWRK}/remap_*
        rm -f ${HYCOMWRK}/n_remap*
        rm -f ${HYCOMWRK}/nn_remap*
        rm -f ${HYCOMWRK}/hycom_*

      fi #end if doIC
    done #end do area(g r)

    rm -f ${HYCOMWRK}/n_hycom_${dtg10}_*.nc
  fi  #end if ${doICfHYCOM}


   tmps=`${Caldtg} ${tmps} 24`
 done
 exit 0
