#!/bin/csh -f
# Christoph Keller, Nov 2013. 

# filename
set infile  = 'soilNOx.fert_res.generic.05x05.nc'
set outfile = 'soilNOx.fert_res.generic.05x05.new.nc'

# select each "level" and write into own file. Change variable name
set i = 1
while ( $i <= 366 )
   cdo seltimestep,$i $infile tmp.nc
   ncdump tmp.nc > tmp.cdl
   sed -i 's/time:units.*/time:units = "days since 2000-01-01 00:00:00" ;/' tmp.cdl 
   sed -i 's/time:calendar.*/time:calendar = "standard" ;/' tmp.cdl 
   sed -i 's/time = 0 ;/time = '$i' ;/' tmp.cdl 
   ncgen -o tmp.nc tmp.cdl
   rm -f tmp.cdl
   if ( $i == 1 ) then
      mv tmp.nc tmp2.nc
   else
      cdo mergetime $outfile tmp.nc tmp2.nc
   endif
   mv tmp2.nc $outfile
   @ i++
end

# merge all files
rm -f tmp*.nc

# exit
unset i
unset infile
unset outfile

exit(0)

# eof
