#!/bin/ksh -x
#
#

typeset -Z6 FctIni FctEnd
typeset -Z3 ftime
FctIni=${1}
FctEnd=${2}

# VARIAVEIS
cd ${Eta_scr}


ftime=${FctIni}
if  [ "${TInitBC}" == "0" ] && [ "${FctIni}" != "000000" ]  ; then    
   Run_Date=`${Eta_home1}/util/caldate.3.0 ${Run_Date} - ${HInitBC}hr 'yyyymmddhh'`
   let ftime=${FctIni}+${HInitBC}
   let FctEnd=${FctEnd}+${HInitBC}
fi

echo "GFS DATA  " ${Run_Date}

ihora=`echo ${Run_Date} |cut -c 9-10`
#ftp://ftpprd.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/gfs.2008081300/

datadir=/data/nccf/com/gfs/prod
server=ftpprd.ncep.noaa.gov
fpref=gfs.t${ihora}z.pgrb2.0p25.f
cd ${Eta_run}

    while ((${ftime}<=${FctEnd})) ; do
#for ftime in 00 06 12 18 24 30 36 42 48;do
      if [ "${ftime}" == "000" ] ; then  
         data_grib=${Eta_home}/data/${CInit}
	 mkdir -p ${data_grib}/${Run_Date}
      else
         data_grib=${Eta_home}/data/${BCond}
      fi
      if [ ! -d ${data_grib}/${Run_Date} ] ; then
        mkdir -p  ${data_grib}/${Run_Date}
      fi
  ifile=gfs.t${ihora}z.pgrb2.0p25.f${ftime}.${Run_Date}.grib2
  if [[ ! -s ${data_grib}/${Run_Date}/${ifile} ]]  ; then
    wget -c http://$server$datadir/gfs.${Run_Date}/$fpref${ftime}
    mv -v  $fpref${ftime} ${data_grib}/${Run_Date}/${ifile}
    chmod 755 ${data_grib}/${Run_Date}/${ifile}
   fi

        let ftime=$ftime+$InitBC

    done



dirdata=`echo ${Run_Date} | cut -c1-6`/`echo ${Run_Date} | cut -c7-10`
#dirdata=`echo ${Run_Date} | cut -c1-10`
datasst=`echo ${Run_Date} | cut -c1-8`
hh=`echo ${Run_Date} | cut -c9-10`
hh2=${hh}
FctCont2=${FctIni}
GlobalOK="False"
First=1
idate1=${Run_Date}
dia_hora=`echo ${Run_Date} | cut -c7-10`

if  [ "${TInitBC}" == "0" ] && [ "${FctIni}" != "000000" ]  ; then    
   let FctCont2=${FctIni}+${HInitBC}
   let FctCont6=${FctIni}+${HInitBC}
else   
   FctCont2=${FctIni}
   FctCont6=${FctIni}
fi

typeset -Z3 FctCont2 
typeset -Z6 FctCont6 



cont=0
while [ "${GlobalOK}" != "True" ] ; do
   if [ "${FctCont2}" == "000" ] ; then  
      data_grib=${Eta_home}/data/${CInit}
   else
      data_grib=${Eta_home}/data/${BCond}   
   fi
   dir_Global=${data_grib}/${Run_Date}
   arqin=${dir_Global}/'gfs.t'${hh2}'z.pgrb2.0p25.f'${FctCont2}'.'${idate1}'.grib2'   
   arqout=${Eta_run}/'gfs.t'${hh}'z.pgrb2.0p25.f'${FctCont6}'.'${Run_Date}'.grib2'   
  if [ -s ${arqin} ] ; then
     echo "ARQ1"$arqin >> ${Eta_run}/cond$Run_Date  
     cp ${arqin} ${arqout}
  fi
  
  if ((${cont}>=100)); then
    echo "cont1"=$cont
    exit 
  fi
  
  if [ -s ${arqin} ] ; then
    cont=0
    
    if [ "${FctCont6}" == "${FctEnd}" ] ; then
      GlobalOK="True"
      exit
    fi  
    let FctCont6=${FctCont6}+${InitBC}
    let FctCont2=${FctCont2}+${InitBC}
  else
   sleep 15
   
   let cont=$cont+1  
  fi
done

