#!/usr/bin/perl -w
# convert timeseries (<yr><mon><q>) in cfs to one in kaf
# tailored to VIC routing model output files
# AWW-1204

@DaysInMon = (-99, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); #no leapyr

if(@ARGV != 1){
  die "Use 1 ARG: <monthly flow t-series (AF) with fmt [y m q] >\n";
}

# input arguments
open (AF, "<$ARGV[0]") or die "can't open input file $ARGV[0]: $!\n";
open (CFS, ">$ARGV[0].cfs") or die "can't open output file $ARGV[0].cfs: $!\n";

# READ tser ----
while (<AF>) {
    ($yr, $mo, $q) = split;
    if (($yr % 4 == 0) || ($yr % 400) == 0){
	$DaysInMon[2] = 29;
    }   
    if($q<0) {  # assume a neg flow is a void, and don't convert (e.g., -99)
	printf CFS "%4d %2d %10.3f\n", $yr, $mo, $q;
    } else {    # regular flow
	printf CFS "%4d %2d %10.3f\n", $yr, $mo, ($q/1.9835/$DaysInMon[$mo]);
    }
}
close(CFS);
close(AF);
