#!/bin/csh -fv
##QSUB -l mpp_p=2 -q ded_1 -lt 40000 -lT 43000 -lM 60Mw -lm 60Mw -eo

set echo
set verbose

# This script computes the initia Temp and Salt condition from Levitus
#     for a new grid: 

#1) Set up these parameters to run:
  set user = yeager
  set GRID = gx1v5
  set GRIDDIR = /fis/cgd/oce/yeager/POP_grids/gx1v5.006/grid
  set TOPOFILE = /fis/cgd/oce/yeager/POP_grids/gx1v5.006/grid/topography_20061229.ieeei4

#2) cd to a temporary directory; get needed files etc.
  if !(-d $GRIDDIR)  mkdir -p $GRIDDIR
  set DIR = /ptmp/$user/$GRID
  if !(-d $DIR)  mkdir -p $DIR
  cd $DIR 

#3) Get POLES 1x1 data off Mass Store:
# msread PHC2_TEMP.nc /HECHT/POLES/PHC2_TEMP.nc
# msread PHC2_SALT.nc /HECHT/POLES/PHC2_SALT.nc

#4)Make namelist :
cat > PHC2_${GRID}_nml << EOFINPUT1
&regrid_nml
  src_file = 'PHC2_TEMP.nc'
  src_var  = 'TEMP'
  dst_imt  = 320
  dst_jmt  = 384
  dst_km   =  60
  dst_horiz_grid_file = '${GRIDDIR}/horiz_grid_20010402.ieeer8'
  dst_vert_grid_file  = '${GRIDDIR}/gx1v5_vert_grid'
  dst_topography_file = '${GRIDDIR}/topography_20061229.ieeei4'
  dst_region_mask_filename = '${GRIDDIR}/region_mask_20061229.ieeei4'
  dst_file     = 'PHC2_TEMP_${GRID}.nc'
  dst_lclobber = .true.
/

&regrid_nml
  src_file = 'PHC2_SALT.nc'
  src_var  = 'SALT'
  dst_file     = 'PHC2_SALT_${GRID}.nc'
  dst_lclobber = .true.
/
EOFINPUT1

#5)Run Program and cp to GRIDDIR:
    
# /fs/cgd/data0/klindsay/regrid/regrid < PHC2_${GRID}_nml 
  /fis/cgd/oce/yeager/POP_tools/regrid/regrid_kl < PHC2_${GRID}_nml 

#6)Send Data to Mass Store:

# mswrite -w brady -t3650 PHC2_TEMP_${GRID}.nc \
#     /BRADY/ccsm/DATA/POLES/PHC2_TEMP_${GRID}.nc
# mswrite -w brady -t3650 PHC2_SALT_${GRID}.nc \
#     /BRADY/ccsm/DATA/POLES/PHC2_SALT_${GRID}.nc

#6) make matlab program and run:
cat > gen_ic.m << EOFINPUT2
T_in_file = 'PHC2_TEMP_${GRID}.nc' ;
S_in_file = 'PHC2_SALT_${GRID}.nc' ;
out_file = 'PHC2_jan_ic_${GRID}.ieeed' ;

fid_out = fopen(out_file, 'w+');

fid_in = netcdf(T_in_file, 'nowrite');
km = length(fid_in{'depth'}(:));
for k=1:km,
   slab = transpose(fid_in{'TEMP'}(1,k,:,:));
   fwrite(fid_out,slab,'double');
end;
close(fid_in);

fid_in = netcdf(S_in_file, 'nowrite');
km = length(fid_in{'depth'}(:));
for k=1:km,
   slab = transpose(fid_in{'SALT'}(1,k,:,:));
   fwrite(fid_out,slab,'double');
end;
close(fid_in);

fclose(fid_out);
EOFINPUT2

cp /home/tempest/klindsay/matlab/startup.m tmp.m
cat gen_ic.m >>! tmp.m
mv -f tmp.m gen_ic.m

matlab < gen_ic.m

exit(0)

