#!/bin/csh
# setpal

setenv SETDIR ${gsmSetDir}
setenv HOMEx ${gsmDir}
setenv HOMEdat /gpfs/ltarasov/lev

set orby=$4
set currentIter = $6
set maxIter = $7

cat <<EOF
################################################
## GSM Run

EOF

cd ${execGSM} && echo "cd ${execGSM}"

echo "GSM starts at " `date`

# set argv=($1 $2 $3 $4 $5)
# if ( `echo "${currentIter}*${dOrby}" | bc` < 100 ) then
#     echo "## GSM skips until LOVECLIM runs for 100 years."
# else if ( `echo "${currentIter}*${dOrby}" | bc` == 100 )
#     echo "## rsiNE.init $1 $2 $3 $4 $5"
#     source rsiNE.init
# else if ( ${currentIter} < ${maxIter} ) then
#     echo "## rsiNE.step $1 $2 $3 $4 $5"
#     source rsiNE.step
# else 
#     source rsiNE.endjob
# endif

if ( ${currentIter} == 1 ) then
    echo "iteration 1 of ${maxIter}"
    if ( ${era} == "LGM" ) then
	echo "Running rsiNE.restart $1 $2 $3 $4 $5"
	set argv=($1 $2 $3 $4 $5)
	source rsiNE.restart
    else
	echo "Running rsiNE.init $1 $2 $3 $4 $5"
	set argv=($1 $2 $3 $4 $5)
	source rsiNE.init
    endif
else if ( ${currentIter} < ${maxIter} ) then
    # if ( ${cnt} == 0 ) then
    	echo "iteration ${currentIter} of ${maxIter}"
    	echo "Running rsiNE.step $1 $2 $3 $4 $5"
    	set argv=($1 $2 $3 $4 $5)
    	source rsiNE.step
    # else
    # 	echo "iteration ${currentIter} of ${maxIter}"
    # 	echo "Running rsiNE.restart $1 $2 $3 $4 $5"
    # 	set argv=($1 $2 $3 $4 $5)
    # 	source rsiNE.restart
    # endif
else
    echo "iteration ${currentIter} (last)"
    echo "Running rsiNE.endjob $1 $2 $3 $4 $5"
    set argv=($1 $2 $3 $4 $5)
    source rsiNE.endjob
endif

echo "GSM ends at " `date`


## Check if GSM ends successfully
tail -1 ${strDir}/${no}/main/GSM/out* | grep "GSM end of RUN EXIT" >/dev/null
set chk=$?
if ( -e fort.201 && ${chk} == 0 ) then
    rm -v fort.360 fort.365

    cat <<EOF

## GSM Run
################################################

EOF
else
    echo "## GSM NOT successfull!"
    exit 1
endif
