#!/bin/ksh
#
#@ shell            = /usr/bin/ksh
#@ class            = ns
#@ job_type         = serial
#@ job_name         = prepare_atm_ic
#@ output           = $(job_name).$(jobid).log
#@ error            = $(job_name).$(jobid).log
#@ notification     = error
#@ resources        = ConsumableCpus(1) ConsumableMemory(1200mb)
#@ wall_clock_limit = 24:00:00
#@ queue
#

set -xuve
date
tar="/opt/freeware/bin/tar"

# b0ga
#grid=T255L62
#expid=b0ga
#src=ec:/xes/public/longrange/$expid

# b0io
grid=T255L91
expid=b0io
src=ec:/xes/public/longrange/$expid

dst=ec:/c3m/ic/atmos/$grid/$expid
cup=$(pwd)
list=$cup/$expid

# Gather the list of original ic's
if [[ ! -a ${list} ]]; then
 emkdir -p $dst
 # b0gc
 #els $src > $list
 # b0io
 for y in $(seq 1993 2009); do
  months="05 11"
  for m in $months; do
   files=$(els $src/${y}${m}0100)
   for f in $files; do
    echo "${y}${m}0100/$f" >> $list
   done
  done
 done  
 #exit
fi

tmp=$TMPDIR/prepare_atm_ic_$expid
rm -rf $tmp
mkdir -p $tmp
cd $tmp

# Prepare and store the ic's after reformatting properly
for l in $(cat $list); do
 # start
 ecp $src/$l .
 ic=$(ls -1 *.tar | cut -d '.' -f 1) 
 $tar -xvf $ic.tar
 for f in $(ls -1 $ic); do
  case $f in
   ICMSH*T|shml*|pua*)  mv $ic/$f ICMSHXXXXINIT ;;
   ICMGG*T|ggsfc*|psu*) mv $ic/$f ICMGGXXXXINIT ;;
   ICMGG*UA|ggml*)      mv $ic/$f ICMGGXXXXINIUA ;;
   ICMCL*T)             mv $ic/$f ICMCLXXXXINIT ;;
  esac
 done
 case $expid in
  b0ga)
   exp=$(echo $ic | cut -d '_' -f 1)
   mem=$(echo $ic | cut -d '_' -f 4)
   ymds=$(echo $ic | cut -d '_' -f 5)
  ;;
  b0io)
   exp=$(echo $ic | cut -d '_' -f 1)
   mem=$(echo $ic | cut -d '_' -f 3)
   ymds=$(echo $ic | cut -d '_' -f 4)
  ;;
  *)
   echo "!!!caution!!!"
   exit 1
  ;;
 esac
 nic=${exp}_${mem}_${ymds} # new name of initial condition
 $tar -cvzf $nic.tar.gz *XXXX*
 ecp $nic.tar.gz $dst
 # end
 rm -rf *${ic}* *${nic}* *XXXX*
 cat ${list} | sed -e '1d' > ${list}.tmp
 mv ${list}.tmp ${list}
done
rm ${list}
cd; rm -rf $tmp

date

