#!/usr/bin/env perl

if (@ARGV != 2) { die "USAGE: mktrans (start) (stop)\n" ;}

$start = $ARGV[0];
$stop  = $ARGV[1];

@photcodes = ("B", "V", "R", "I", "Z"); 

foreach $code (@photcodes) {

    @list = `photsearch -trange $start $stop -photcode $code`;

    # the lines from photsearch look like this:
    # V 2001/02/03,15:38:53  26.249  0.017 elixir

    @dates = ();

    # use date hashes to extract stats for each date:
    foreach $line (@list) {
	
	# parse the line for the date
	@words = split (" ", $line);
	($date) = $words[1] =~ /(\d\d\d\d\/\d\d\/\d\d),/;
	
	# if this is a new date, save it in the list
	unless ($sum1{$date}) { @dates = (@dates, $date); }

	# add to the stats 
	$sumN{$date} ++;
	$sum1{$date} += $words[2];
	$sum2{$date} += $words[2]*$words[2];

	# print STDERR "date: $date\n";

    }

    @sdates = sort by_date @dates;

    # calculate mean and stdev for each date
    foreach $date (@sdates) {
	
	$Np  = $sumN{$date};
	$zp  = $sum1{$date} / $Np;
	$dzp = sqrt ($sum2{$date} / $Np - $zp*$zp);

	printf STDOUT "transreg %s %6.3f %6.4f %s 1d\n", $code, $zp, $dzp, $date;
    }

    %sumN = ();
    %sum1 = ();
    %sum2 = ();
    print STDOUT "\n";
    
}

exit 0;

sub by_date {
    
    ($year, $month, $day) = $a =~ /(\d\d\d\d).(\d\d).(\d\d)/;
    $va = get_jd ($year, $month, $day);
    ($year, $month, $day) = $b =~ /(\d\d\d\d).(\d\d).(\d\d)/;
    $vb = get_jd ($year, $month, $day);
    $va <=> $vb;
}
    


###################################################################################

sub vsystem {
    print STDERR "@_\n";
    $status = system ("@_");
    $status;
}

sub goodbye {
    die "@_\n";
}


sub get_jd {

    my($year) = $_[0];
    my($month) = $_[1];
    my($day) = $_[2];

    my($jd) = $day - 32075 + int (1461*($year + 4800 + int (($month - 14)/12))/4)
	+ int(367*($month - 2 - int(($month - 14)/12)*12)/12)
	    - int(3*int(($year + 4900 + int(($month - 14)/12))/100)/4) - 0.5;
    

    return ($jd);

}

sub get_mjd {

    my($year) = $_[0];
    my($month) = $_[1];
    my($day) = $_[2];

    my($jd) = $day - 32075 + int (1461*($year + 4800 + int (($month - 14)/12))/4)
	+ int(367*($month - 2 - int(($month - 14)/12)*12)/12)
	    - int(3*int(($year + 4900 + int(($month - 14)/12))/100)/4) - 0.5 - 2400000.5;
    

    return ($jd);

}

