#!/usr/bin/env perl
$SKIPDOME = 0;

if (@ARGV != 6) { die "ERROR: USAGE: imselect (type) (filter) (tstart) (tend) (output) (SPLIT | MEF)\n" }

$type   = "\U$ARGV[0]\E";
$filter = "\U$ARGV[1]\E";
$start  = $ARGV[2];
$stop   = $ARGV[3];
$output = $ARGV[4];
$mode   = $ARGV[5];

unless ($output =~ /CCDNUM/) { die "ERROR: output file needs CCDNUM component\n"; }

if (($mode ne "MEF") && ($mode ne "SPLIT")) { die "ERROR: mode must be either -split or -mef\n"; }

if ($type eq "DARK") { }

if ($type eq "FLAT") {
    # define some of the relevant parameters
    $max = 60000;

    $tmp = `filtnames $filter`; chop $tmp;
    if ($?) { die "ERROR: invalid filter $filter\n"; }
    $filter = $tmp;

    # recipe file defines detrend types & cutoff exptime values
    $recipefile = `gconfig DETREND_RECIPES`; chop $recipefile;
    if ($?) { die "ERROR: missing DETREND_RECIPES in configuration\n"; }

    ($tmp, $tmp, $extras) = split (" ", `gconfig -c $recipefile $filter`);
    if ($?) { die "ERROR: missing detrend recipe for $filter\n"; }

    # all filters have 'flat', grab extras:
    ($detype, $minflux, $min) = split (",", $extras);
    if ("\U$detype\E" ne "FLAT") { die "ERROR: flat extras are missing\n"; }
}

$CCDWORD      = `gconfig CCDNUM-KEYWORD`; chop $CCDWORD;
$CHIPSKIP     = `gconfig CHIP_SKIP_LIST`; chop $CHIPSKIP;
@chipskip = ();
if (-e $CHIPSKIP) { 
    open (FILE, $CHIPSKIP);
    @chipskip = <FILE>;
    close (FILE);
    foreach $chip (@chipskip) { chop $chip; }
}

# relevant camera parameters
$Nccd = `cameraconfig -Nccd`; chop ($Nccd);
if ($?) { die "error in config\n"; }

($Naxis1, $Naxis2) = split (" ", `cameraconfig -axes`);
if ($?) { die "error in config\n"; }

@ccds = split (" ", `cameraconfig -ccds`);
if ($?) { die "error in config\n"; }

@ccdn = split (" ", `cameraconfig -ccdn`);
if ($?) { die "error in config\n"; }

@good = ();
@marginal = ();

# define filter lines for imsearch.  for flats, there may be alternate filter names to test
@filtline = ();
if ($type eq "FLAT") {
    # convert given filter name to list of possible names:
    @filtlist = split (" ", `filtnames $filter -all`);
    foreach $filt (@filtlist) {
	push @filtline, "-type flat -filter $filt -mode $mode -trange $start $stop";
    }
} 
if ($type eq "BIAS") {
    push @filtline, "-type bias -mode $mode -trange $start $stop";
} 
if ($type eq "DARK") {
    push @filtline, "-type dark -etime $ARGV[1] -mode $mode -trange $start $stop";
} 

# run selection on each possible $filtline
@list = ();
foreach $line (@filtline) {
    @tlist = `imsearch -ccd $ccds[0] $line`;
    @list = (@list, @tlist);
}
$Nlist = @list;
print STDERR "found $Nlist images\n";

FRAME:
foreach $frame (@list) {
    @words = split (" ", $frame);

    # skip domeflat images
    if ($SKIPDOME && ($type eq "FLAT")) {
	# a fairly lame and non-robust way to detect dome flats
	@answer = `echo $words[4]/$words[5] | fields OBJECT | grep -i dome`;
	if ($answer[0] ne "") { print STDERR "$words[5] rejected: dome flat\n"; next FRAME; }
	
	# test for acceptable time (or is probably a dome flat)
	$answer = `dusktime $words[8]`;
	($tmp, $tmp, $dt) = split (" ", $answer);
	if ($dt < 0) { print STDERR "$words[5] rejected: not twilight\n"; next FRAME; }
    }

    # image(s) must exist on disk:
    if ($mode eq "SPLIT") {
	# all $Nccd images must exist on disk, split files are assumed to be 
	# in a subdirectory of their own, .fits extension assumed
	@answer = <$words[4]/*.fits>;
	if (@answer != $Nccd) { print STDERR "$words[5] rejected: missing images\n"; next FRAME; }
    } else {
	# base file should exist:
	if (! -e "$words[4]/$words[5]") { print STDERR "file $words[4]/$words[5] missing, skipping\n"; next FRAME; }
    }

    # images have to have the correct dimensions
    if ($mode eq "SPLIT") {
	($tmp, $Nx, $Ny) = split (" ", `echo $words[4]/$words[5] | fields NAXIS1 NAXIS2`);
    } else {
	($tmp, $Nx, $Ny) = split (" ", `echo $words[4]/$words[5] | fields -x 0 NAXIS1 NAXIS2`);
    }
    if ($?) { print STDERR "failure to find NAXIS1, NAXIS2 in file $words[4]/$words[5], skipping\n"; next FRAME; }
    if ($Nx != $Naxis1) { print STDERR "$words[5] rejected: wrong dimensions\n"; next FRAME; }
    if ($Ny != $Naxis2) { print STDERR "$words[5] rejected: wrong dimensions\n"; next FRAME; }
    
    # must have Nccd entries in db:
    if ($mode eq "SPLIT") { 
	@answer = split ("/", $words[4]); 
	$match = $answer[-1]; 
    } else { 
	$match = $words[5]; 
    }
    @list2 = `imsearch -name $match`;
    if (@list2 != $Nccd) { print STDERR "$words[5] rejected: missing entries in image database\n"; next FRAME; }

    # test flux levels for FLATS
    if ($type eq "FLAT") {
       CHIP:  # check for counts or flux out of range or any chip
	foreach $chip (@list2) {
	    @words2 = split (" ", $chip);
	    foreach $chipskip (@chipskip) { 
		if ($words2[3] eq $chipskip) { next CHIP; }
	    }
	    
	    # test for acceptable counts range
	    if ($words2[11] < $min) { print STDERR "$words[5] rejected: signal too low: $words2[11] vs $min\n"; next FRAME; }
	    if ($words2[11] > $max) { print STDERR "$words[5] rejected: signal too high: $words2[11] vs $max\n"; next FRAME; }
	    
	    # test for acceptable flux
            if ($words2[7] > 0.0) {
	       $Flux = $words2[11] / $words2[7];
	    } else {
	       $Flux = 0.0;
	    }
	    if ($Flux < $minflux) { print STDERR "$words[5] rejected: flux too low: $Flux vs $minflux\n"; next FRAME; }
	}
    }
    # test bias levels for BIAS / DARK
    if (($type eq "BIAS") || ($type eq "DARK")) {
       CHIP:  # check for values in bias column
	foreach $chip (@list2) {
	    @words2 = split (" ", $chip);
	    if ($words2[10] == 0.0) { print STDERR "$words[5] rejected: no imstats\n"; next FRAME; }
	}
    }

    # add good images to the output lists (use CCD N for output filenames, CCD ID for [extname] in mef files)
    # entries are not guaranteed to be in CCD N sequence

    foreach $line (@list2) {
	@words2 = split (" ", $line);
	$ccdid  = $words2[3];
	if ($mode eq "MEF") {
	    @$ccdid = (@$ccdid, "$words2[4]/$words2[5]\[$ccdid]");
	} else {
	    @$ccdid = (@$ccdid, "$words2[4]/$words2[5]");
	}
    }
    if (($type eq "BIAS") && (@$ccdid > 30)) { last FRAME; }
    if (($type eq "DARK") && (@$ccdid > 30)) { last FRAME; }
    if (($type eq "FLAT") && (@$ccdid > 50)) { last FRAME; }
}

# write output to Nccd list files 
for ($i = 0; $i < $Nccd; $i++) {
    $ccd   = $ccdn[$i];
    $ccdid = $ccds[$i];

    $name = $output;
    $name =~ s/CCDNUM/$ccd/;

    open (LIST, ">$name");
    foreach $line (@$ccdid) {
	print LIST "$line\n";
    } 
    close (LIST);
}
print STDERR "SUCCESS\n\n";
exit 0;

# we need to select the list of images which satisfy a few criteria:
# 1) all 12 CCDs must exist
# 2) stats must be measured for each
# 3) stats for all 12 must be within range (2000 - 40000)
# 4) NAXIS1 == 2080 && NAXIS2 == 4128


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

sub goodbye {
    print STDERR "ending execution\n";
    die "@_";
}

