#!/usr/sbin/perl -w

#$dataDirectory = "/Net/Movies0/grant/diverg/nscat/divfiles/";
$dataDirectory = "/Net/NSCAT/people/grant/divfiles/";
$saveDirectory = "/Net/NSCAT/people/grant/diverg/swaths/";

my ( @data, @time );

open ( DIM, "/Net/Movies0/grant/diverg/nscat/others/dimensions.dat" ) ||
    die "Can't do it.";

while ( <DIM> ) {                             
    chomp();
    @line = split();
    $line[0] =~ s/\D+//;
    $line[0] =~ s/\D+//;
    $dimensions{"$line[0]"} = $line[1];
}
close(DIM);

for ( $year = 1996; $year <= 1997; $year++ ) {
    for ( $day = 0; $day <= 366; $day++ ) {
	$fileName = "";
	if ( $day < 10 ) {
	    $fileName = $year."00".$day;
	}
	elsif ( $day < 100 ) {
	    $fileName = $year."0".$day;
	}
	else {
	    $fileName = $year.$day;
	}
	
	$file = $dataDirectory.$fileName.".div";
	$numrows = $dimensions{"$fileName"};

	if ( open ( DIV, $file ) ) {
	    for ( $row = 0; $row < $numrows; $row++ ) {
		for ( $col = 0; $col < 48; $col++ ) {
		    $line = <DIV>;
		    @fields = split(/\s+/,$line);
		    $data[0][$row][$col] = $fields[1];
		    $data[1][$row][$col] = $fields[2];
		    $data[2][$row][$col] = $fields[3];
		    $time[$row] = $fields[4];
		}
	    }
	    close(DIV);
	    $newFile = $saveDirectory.$fileName.".div";
	    open ( OUTPUT, ">$newFile" );
	    print OUTPUT "$numrows 48\n";
	    for ( $i = 0; $i < 3; $i++ ) {
		for ( $row = 0; $row < $numrows; $row++ ) {
		    for ( $col = 0; $col < 48; $col++ ) {
			printf OUTPUT "%10.3f", $data[$i][$row][$col];
		    }
		    print OUTPUT "\n";
		}
		print OUTPUT "\n";
	    }
	    for ( $row = 0; $row < $numrows; $row++ ) {
		print OUTPUT $time[$row]." ";
	    }
	    print OUTPUT "\n";
	    close(OUTPUT);
	    system "gzip", $newFile;
	    print "Done with $newFile\n";
	}
    }
}

