#!/usr/bin/env perl

sub usage {
    # input is foo.fits
    # outputs are outroot.im.fits (image) outroot.ob.fits (object list), outroot.log, etc
    print STDERR "USAGE: phase2 (input) (outroot)\n";
    exit 2;
}

if (@ARGV != 4) { &usage; }

# base file needs to be hardwired, from environment, or based on program name
$base   = psMetadataParseConfig (NULL, basefile, FALSE);  

# probably defined in the base file?
$site   = psMetadataParseConfig (NULL, sitefile, FALSE);  

# this should be optionally specified as part of the command-line options
# alternatively, this should be derived from the input file header data 
$camera = psMetadataParseConfig (NULL, camerafile, FALSE);

# we need a way to define an optional alternative recipe
$recipe = psMetadataParseConfig (NULL, recipefile, FALSE);  # defined in the camera file

# load only the headers from the given file input a list of headers
@headers = psFITSReadHeaderSet ($input);

# check the validity of the given set of headers based on expectactions for this camera
# ** where does camera come from?
# ** how do we do this if the camera is derived from the header info?
$status = pmCameraValidateHeaders ($headers, $camera);

# this gets a bit tenuous: what do we do with the collection?  

# construct a complete, empty (ie, no pixel data) FPA structure for this camera / header set
# we need to construct the output container.  is it big enough to fit in memory?  assume so?
$FPA = pmFPAfromHeader ($headers, $camera);

### now we work on individual readouts:

# we have the FPA, already validated
# as part of the FPA, we have access to a specified READOUT and we know the corresponding EXTNAME

# load in the complete readout:
$image    = psImageReadSection (NULL, 0, 0, 0, 0, 0, $extname, $Nreadout, $input);

# load in the complete corresponding bias image (this should be done once per cell)
# in this form, we are implying that the bias image is guaranteed to have the corresponding EXTNAME
$bias     = psImageReadSection (NULL, 0, 0, 0, 0, 0, $extname, 0, $biasname);

# overscan options:
# - overscan is defined by the recipe (BIAS.OVERSCAN has form [Xs,Xe:Ys:Ye])
# - overscan is defined by the header (BIAS.OVERSCAN has value BIASSEC)
# - overscan is not used (BIAS.OVERSCAN has value NONE)

# bias section from header:
$ = psMetadataLookup ($readout->metadata, "BIASSEC");
$overscan = psImageSubsection ($image, $metaitem->data.void);

psListAdd ($overlist, $overscan, PS_LIST_HEAD);

$bias = psImageReadSection (NULL, 0, 0, 0, 0, 0, $extname, -1, $biasname);

$image_b = pmSubtractBias ($image, NULL, $overlist, PM_OVERSCAN_COLUMNS, $stats, 0, PM_FIT_NONE, $bias);

