#!/usr/bin/env perl
# calls flatten.flips, but no direct flips functions

# check the usage
if ($ARGV[0] eq "-h") { usage (); }
if ($ARGV[0] eq "-help") { usage (); }
if (@ARGV != 4) { die "USAGE: fr.detrend (path) (root) (mode) (outdir)\n" }

# assign the command line arguments
$path = $ARGV[0];
$root = $ARGV[1];
$mode = "\U$ARGV[2]\E";
if (($mode ne "MEF") && ($mode ne "SPLIT")) { die "ERROR: mode must be either -split or -mef\n";}
$outdir = $ARGV[3];
if (! -d $outdir) { vsystem ("mkdir -p $outdir"); }

# get info on input image
$basename = mk_basename ($path, $root, $mode);
$Nccd = `cameraconfig -Nccd`; chop ($Nccd);

for ($ccd = 0; $ccd < $Nccd; $ccd++) {
    
    $infile  = mk_filename ($path, $root, $mode, $ccd);
    $outfile = mk_filename2 ($outdir, $root, "SPLIT", $ccd);

    $status = vsystem ("flatten.flips -quiet $infile $outfile $ccd $mode");
    if ($status) { die "ERROR: problem running flatten on $infile\n"; }

}

print STDOUT "SUCCESS: finished with fr.detrend\n";
exit 0;

sub mk_basename {
    my ($path) = $_[0];
    my ($root) = $_[1];
    my ($mode) = $_[2];

    if ($mode eq "MEF") {
	$name = sprintf "%s/%s.fits", $path, $root;
	return $name;
    }
    if ($mode eq "SPLIT") {
	$name = sprintf "%s/%s", $path, $root;
	return $name;
    }
    return "";
}

sub mk_filename {
    my ($path) = $_[0];
    my ($root) = $_[1];
    my ($mode) = $_[2];
    my ($ccd)  = $_[3];

    if ($mode eq "MEF") {
	$name = sprintf "%s/%s.fits", $path, $root;
	return $name;
    }
    if ($mode eq "SPLIT") {
	$name = sprintf "%s/%s/%s%02d.fits", $path, $root, $root, $ccd;
	return $name;
    }
    return "";
}

sub mk_filename2 {
    my ($path) = $_[0];
    my ($root) = $_[1];
    my ($mode) = $_[2];
    my ($ccd)  = $_[3];

    if ($mode eq "MEF") {
	$name = sprintf "%s/%s.fits", $path, $root;
	return $name;
    }
    if ($mode eq "SPLIT") {
	$name = sprintf "%s/%s%02d.fits", $path, $root, $ccd;
	return $name;
    }
    return "";
}

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

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

sub usage {
    print "\n";
    print "USAGE: fr.detrend (path) (root) (mode) (outdir)\n";
    print " path:   path to MEF image or SPLIT dir\n";
    print " root:   root name of image (MEF = root.fits, SPLIT = root/rootNN.fits)\n";
    print " mode:   MEF or SPLIT\n";
    print " outdir: directory for output results (all split)\n";
    exit 1;
}
