#!/bin/csh -f

set THIS_DIR = `pwd`
set OUT_DIR = /home/disk/muggy/data/ncep_reanalysis/pentad
set SRC_DIR = /home/disk/muggy/data/ncep_reanalysis/pentad/tem_daily
set OUTFIL = $OUT_DIR/uwnd.pentad.1948_2002.nc
set INFIL = uwnd
set NCOOPTS = '-O -F'

cd $SRC_DIR

set yr = 1948
set ind1 = 1

while ( $yr <= 2001 )
    
    echo "Year = $yr"
    set pen_ind = 1
    set day_ind = 1
    set fname = $SRC_DIR/$INFIL.$yr.nc

    @ leap = $yr % 4

    while ( $pen_ind <= 73 )

	if ( $leap == 0 && $pen_ind == 12 ) then
	    set ind2 = 6
	else
	    set ind2 = 5
	endif

	if ( $pen_ind < 10 ) then
	    set temfil = $SRC_DIR/temfil.0$pen_ind.nc
	else
	    set temfil = $SRC_DIR/temfil.$pen_ind.nc
	endif

	@ ind1a = $day_ind + $ind1 - 1
	@ ind2a = $day_ind + $ind2 - 1

	ncra $NCOOPTS -d time,$ind1a,$ind2a $fname $temfil

        @ day_ind = $day_ind + $ind2
	@ pen_ind = $pen_ind + 1

    end

    ncrcat -O $SRC_DIR/temfil.??.nc $SRC_DIR/temyrfil.$yr.nc

    /bin/rm $SRC_DIR/temfil.??.nc

    @ yr = ($yr + 1)
end


    echo "Year = $yr"
    set pen_ind = 1
    set day_ind = 1
    set fname = $SRC_DIR/$INFIL.$yr.nc

    @ leap = $yr % 4

    while ( $pen_ind <= 66 )

	if ( $leap == 0 && $pen_ind == 12 ) then
	    set ind2 = 6
	else
	    set ind2 = 5
	endif

	if ( $pen_ind < 10 ) then
	    set temfil = $SRC_DIR/temfil.0$pen_ind.nc
	else
	    set temfil = $SRC_DIR/temfil.$pen_ind.nc
	endif

	@ ind1a = $day_ind + $ind1 - 1
	@ ind2a = $day_ind + $ind2 - 1

	ncra $NCOOPTS -d time,$ind1a,$ind2a $fname $temfil

        @ day_ind = $day_ind + $ind2
	@ pen_ind = $pen_ind + 1

    end

    ncrcat -O $SRC_DIR/temfil.??.nc $SRC_DIR/temyrfil.$yr.nc

    @ yr = ($yr + 1)


echo "Generating one big outfile from yearly files"
ncrcat -O $SRC_DIR/temyrfil.????.nc $OUTFIL

echo "Cleaning up"
/bin/rm temfil.??.nc
/bin/rm temyrfil.????.nc

echo "Done!"
