#!/bin/ksh 

#Functions
ReplaceLine()
{
#!/bin/ksh -x
vi $1 << end
/${2}/
:C
${3}
:w!
:q
end
}
InsertLine_vi()
{
#!/bin/ksh -x
vi $1 << end
:$2
:o
:options template
:w!
:q
end
}

Change_vi()
{
#!/bin/ksh -x
vi $1 << end
:%s/${2}/$3
:w!
:q
end
}

# VARIAVEIS

Fcts=HFCT
typeset -Z4 Fcts
YY=`echo ${Run_Date} |cut -c 1-4`
MM=`echo ${Run_Date} |cut -c 5-6`
DD=`echo ${Run_Date} |cut -c 7-8`
HH=`echo ${Run_Date} |cut -c 9-10`

NARQ=${LabRod}${Res}km_${paramet}_${Run_Date}
ARQIN=`${Eta_home}/util/caldate.3.0 ${Run_Date} + ${Fcts}hr ${NARQ}'+yyyymmddhh'`
ARQOUT=`${Eta_home}/util/caldate.3.0 ${Run_Date} + ${Fcts}hr Indices${Run_Date}'+yyyymmddhh'`
GRBDIR=${Eta_grbctl}
ln -sf ${GRBDIR}/${ARQIN}.grb 

cat << EOF > ${Eta_run}/namelist_grib
 &MODEL_GRIDS 
  lm=${LSM} 
  res=${resol} 
  FreqModOut=${IntFct}  
  IDIA=${DD}
  IMES=${MM}
  IANO=${YY}
  IHORA=${HH}
  ARQIN='${ARQIN}.grb'
  ARQOUT='${ARQOUT}.bin'
  strm_opt=5
 &END
EOF

#cat ${Eta_ucl}/namelist_indice >> ${Eta_run}/namelist_grib
cat ${Eta_ucl}/index_mlevs.txt > ${Eta_run}/index_mlevs.txt

intervalo=`echo ${IntPhisAcum} | cut -d. -f1`

${Eta_exe}/gera_sondagens_modelo_grib.exe
${Eta_exe}/indices.x
Dir_IndSev=${Eta_indsev}
mkdir -p ${Dir_IndSev}
TEMPL=Indices${Run_Date}
if ((${Fcts}==0000)) ; then
  cp ${Eta_run}/${ARQOUT}.ctl ${Eta_run}/${TEMPL}.ctl
cat > head${Run_Date}.ctl << EOF
dset ^${TEMPL}+%y4%m2%d2%h2.bin
options template
EOF
nlinhas=`wc -l ${Eta_run}/${TEMPL}.ctl|awk '{print $1}'`
echo "nlinhas= "${nlinhas}
let nlinhas=${nlinhas}-1
tail -${nlinhas} ${Eta_run}/${TEMPL}.ctl >> head${Run_Date}.ctl
mv -f ${Eta_run}/head${Run_Date}.ctl ${Eta_run}/${TEMPL}.ctl
let NArqs=${Fct}/${intervalo}
let NArqs=${NArqs}+1
Change_vi ${Eta_run}/${TEMPL}.ctl 'TDEF   1' 'Tdef  '${NArqs}
mv ${Eta_run}/${TEMPL}.ctl    ${Dir_IndSev}/.
chmod 755 ${Dir_IndSev}/${TEMPL}.ctl
fi

mv ./${ARQOUT}.* ${Dir_IndSev}/.
chmod 755 ${Dir_IndSev}/*
rm -f ./${ARQIN}.grb 
