#!/usr/bin/env perl

# this program has two jobs:
# 1: for the given exp_tag, generate the binned & mosaiced JPEG images
# 2: examine the collection of per-imfile statistics and reject.  At the moment, 
#    this program (and the database) only allows rejection at the exposure level,
#    not at the imfile level. 

use Carp;
use warnings;
use strict;

## report the program and machine
use Sys::Hostname;
my $host = hostname();
print "\n\n";
print "Starting script $0 on $host\n\n";

use vars qw( $VERSION );
$VERSION = '0.01';

use IPC::Cmd 0.36 qw( can_run run );             # tools to run UNIX programs with control over I/O
use PS::IPP::Metadata::Config;                   # tools to parse the psMetadataConfig files
use PS::IPP::Metadata::List qw( parse_md_list ); # ?
use Statistics::Descriptive;                     # tools for calculating basic statistical quantities
use File::Temp qw( tempfile );                   # tools to construct temp files
use PS::IPP::Config qw($PS_EXIT_SUCCESS          
		       $PS_EXIT_UNKNOWN_ERROR
		       $PS_EXIT_SYS_ERROR
		       $PS_EXIT_CONFIG_ERROR
		       $PS_EXIT_PROG_ERROR
		       $PS_EXIT_DATA_ERROR
		       $PS_EXIT_TIMEOUT_ERROR
		       caturi
		       );                        # tools to parse the IPP configuration information
my $ipprc = PS::IPP::Config->new(); # IPP configuration

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt ); # option parsing
use Pod::Usage qw( pod2usage ); 

# parse the command-line options
my ($det_id, $iter, $exp_tag, $det_type, $camera, $filter, $reject, $dbname, $workdir, $no_update, $no_op);
GetOptions(
	   'det_id|d=s'        => \$det_id,
	   'iteration=s'       => \$iter,
	   'exp_tag|e=s'       => \$exp_tag,
	   'det_type|t=s'      => \$det_type,
	   'camera=s'          => \$camera,
	   'filter=s'          => \$filter,
	   'reject'            => \$reject,
	   'dbname|d=s'        => \$dbname, # Database name
	   'workdir|w=s'       => \$workdir, # Working directory, for output files
	   'no-update'         => \$no_update,
	   'no-op'             => \$no_op,
	   ) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage(
	  -msg => "Required options: --det_id --iteration --exp_tag --det_type --camera",
	  -exitval => 3,
	  ) unless defined $det_id
    and defined $iter
    and defined $exp_tag
    and defined $det_type
    and defined $camera;

# load IPP config information for the specified camera
$ipprc->define_camera($camera);

# Recipes to use, as a function of the detrend type
use constant RECIPES => {
    'bin1' => {		# We're creating a master --- already processed the input
	'bias'     => 'PPIMAGE_J1_RESID_B',	# Bias only
	'dark'     => 'PPIMAGE_J1_RESID_B',	# Dark only
	'shutter'  => 'PPIMAGE_J1_RESID_F',	# Shutter only
	'flat'     => 'PPIMAGE_J1_RESID_F',	# Flat-field only
	'domeflat' => 'PPIMAGE_J1_RESID_F',	# Flat-field only
	'skyflat'  => 'PPIMAGE_J1_RESID_F',	# Flat-field only
	'fringe'   => 'PPIMAGE_J1_RESID_R',	# Fringe only
    },
    'bin2' => {		# We're checking the master --- input is not already processed
	'bias'     => 'PPIMAGE_J2_RESID_B',	# Bias only
	'dark'     => 'PPIMAGE_J2_RESID_B',	# Dark only
	'shutter'  => 'PPIMAGE_J2_RESID_F',	# Shutter only
	'flat'     => 'PPIMAGE_J2_RESID_F',	# Flat-field only
	'domeflat' => 'PPIMAGE_J2_RESID_F',	# Flat-field only
	'skyflat'  => 'PPIMAGE_J2_RESID_F',	# Flat-field only
	'fringe'   => 'PPIMAGE_J2_RESID_R',	# Fringe only
    },
};

# Look for programs we need
my $missing_tools;
my $dettool = can_run('dettool') or (warn "Can't find dettool" and $missing_tools = 1);
my $ppImage = can_run('ppImage') or (warn "Can't find ppImage" and $missing_tools = 1);
if ($missing_tools) { 
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR); 
}

# Parser for psMetadataConfig files (used for output from dettool)
my $mdcParser = PS::IPP::Metadata::Config->new;	

# Get list of imfile files
my $files;			# Array of imfile files
{
    # dettool command to select imfile data for this exp_tag
    my $command = "$dettool -residimfile";
    $command .= " -det_id $det_id";
    $command .= " -iteration $iter";
    $command .= " -exp_tag $exp_tag";
    $command .= " -dbname $dbname" if defined $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	warn("Unable to perform dettool -residimfile: $error_code\n");
	exit($error_code);
    }
    # XXX report an error message if stdout_buf is empty

    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR);

    $files = parse_md_list($metadata) or
	&my_die("Unable to parse metadata list", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR);
}

# Output products
$workdir = caturi( $workdir, "$camera.$det_type.$det_id" ) if defined $workdir;
my $outputRoot = $ipprc->file_prepare( "$exp_tag/$exp_tag.detresid.$det_id.$iter", $workdir, ${$files}[0]->{path_base} );
my $jpeg1Name  = $ipprc->filename("PPIMAGE.JPEG1", $outputRoot); # Binned JPEG #1
my $jpeg2Name  = $ipprc->filename("PPIMAGE.JPEG2", $outputRoot); # Binned JPEG #2
my $logName    = $ipprc->filename("LOG.EXP", $outputRoot); # Name for log

my $logFile;
unless ($no_op) {
    # XXX this will fail if the file exists (because of Nebulous rules)
    $logFile = $ipprc->file_create_append( $logName );
}

#### build the JPEG images ####

# XXX in debug mode, unlink = 0
my ($list1File, $list1Name) = tempfile( "$exp_tag.detresid.$det_id.$iter.b1.list.XXXX", UNLINK => 1 );
my ($list2File, $list2Name) = tempfile( "$exp_tag.detresid.$det_id.$iter.b2.list.XXXX", UNLINK => 1 );
foreach my $file (@$files) {
    print $list1File ($ipprc->filename( "PPIMAGE.BIN1", $file->{path_base}, $file->{class_id} ) . "\n");
    print $list2File ($ipprc->filename( "PPIMAGE.BIN2", $file->{path_base}, $file->{class_id} ) . "\n");
}
close $list1File;
close $list2File;

# Recipes to use in processing
my $recipe1 = RECIPES->{"bin1"}->{lc($det_type)};
&my_die("Unrecognised detrend type: $det_type", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR) unless defined $recipe1;

my $recipe2 = RECIPES->{"bin2"}->{lc($det_type)};
&my_die("Unrecognised detrend type: $det_type", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR) unless defined $recipe2;

unless ($no_op) {

    # Make the jpeg for binning 1
    {
	my $command = "$ppImage -list $list1Name $outputRoot -recipe PPIMAGE $recipe1"; # Command to run
	my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	    run(command => $command, verbose => 1);
	unless ($success) {
	    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	    &my_die("Unable to run ppImage: $error_code", $det_id, $iter, $exp_tag, $error_code);
	}
	&my_die("Unable to find expected output file: $jpeg1Name", $det_id, $iter, $exp_tag, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($jpeg1Name);
    }
    
    # Make the jpeg for binning 2
    {
	my $command = "$ppImage -list $list2Name $outputRoot -recipe PPIMAGE $recipe2"; # Command to run
	my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	    run(command => $command, verbose => 1);
	unless ($success) {
	    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	    &my_die("Unable to run ppImage: $error_code", $det_id, $iter, $exp_tag, $error_code);
	}
	&my_die("Unable to find expected output file: $jpeg2Name", $det_id, $iter, $exp_tag, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($jpeg2Name);
    }
}

#### measure stats and reject if needed ####

# Rejection thresholds & related data
my $expected                = rejection_limit( 'EXPECTED',         $det_type, $filter );
my $reject_imfile_mean      = rejection_limit( 'IMFILE.MEAN',      $det_type, $filter );
my $reject_imfile_flux      = rejection_limit( 'IMFILE.FLUX',      $det_type, $filter );
my $reject_imfile_stdev     = rejection_limit( 'IMFILE.STDEV',     $det_type, $filter );
my $reject_imfile_meanstdev = rejection_limit( 'IMFILE.MEANSTDEV', $det_type, $filter );
my $reject_imfile_sn        = rejection_limit( 'IMFILE.SN',        $det_type, $filter );
my $reject_imfile_bin_stdev = rejection_limit( 'IMFILE.BIN.STDEV', $det_type, $filter );
my $reject_imfile_bin_sn    = rejection_limit( 'IMFILE.BIN.SN',    $det_type, $filter );
my $reject_exp_mean         = rejection_limit( 'EXP.MEAN',         $det_type, $filter );
my $reject_exp_flux         = rejection_limit( 'EXP.FLUX',         $det_type, $filter );
my $reject_exp_stdev        = rejection_limit( 'EXP.STDEV',        $det_type, $filter );
my $reject_exp_meanstdev    = rejection_limit( 'EXP.MEANSTDEV',    $det_type, $filter );
my $reject_exp_sn           = rejection_limit( 'EXP.SN',           $det_type, $filter );
my $reject_exp_bin_stdev    = rejection_limit( 'EXP.BIN.STDEV',    $det_type, $filter );
my $reject_exp_bin_sn       = rejection_limit( 'EXP.BIN.SN',       $det_type, $filter );

# storage variables
my @means;			# Array of means
my @fluxes;			# Array of means / exptimes
my @variances;			# Array of variances
my @binVariances;		# Array of binned variances
my @meanStdevs;			# Array of mean stdevs
my @names;			# Array of names (class_id)

# load the arrays from the imfile output table
foreach my $file (@$files) {
    push @means,      	$file->{bg};                           # mean background counts
    if ($file->{exp_time} > 0.0) {
	push @fluxes,     	$file->{bg} / $file->{exp_time};       # mean background counts / sec
    } else {
	push @fluxes,     	$file->{bg};
    }
    push @meanStdevs, 	$file->{bg_mean_stdev};                # stdev of the mean counts (for imfile components)
    push @variances,  	$file->{bg_stdev}*$file->{bg_stdev};   # total variance from all imfile components
    push @binVariances, $file->{bin_stdev}*$file->{bin_stdev}; # total variance of binned images over all imfile components
    push @names,        $file->{class_id};                     # name of the component
}

# Reject based on the stats of the imfiles
# it is VALID to reject on more than one criterion
&my_die("Number of means and number of variances differ!", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR) unless scalar @means == scalar @variances;
for (my $i = 0; $i < scalar @means; $i++) {
    my $flux = $fluxes[$i];	# Flux for this imfile
    my $mean = $means[$i];	# Mean for this imfile
    $mean -= $expected;
    my $stdev = sqrt($variances[$i]);	# Stdev for this imfile
    my $binStdev = sqrt($binVariances[$i]);	# Stdev for this imfile
    my $name = $names[$i];

    last if $no_op;

    # reject exposure if, for any imfiles, the mean residual counts
    # deviate from the expected value by more than N sigma, (sigma =
    # total pixel variance).  this test is sensible for images which
    # should have a predictable nominal residual mean count value (eg,
    # 0.0 for a bias).   in general, use with ADDITIVE components
    if ($reject_imfile_mean > 0) {
	if (abs($mean) > $reject_imfile_mean * $stdev) {
	    print $logFile "Rejecting exposure based on bad imfile mean for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile mean for $name meets requirements: ";
	}
	print $logFile "$mean vs $reject_imfile_mean * $stdev\n";
    }  else {
	print $logFile "No rejection on imfile mean for $name\n";
    }

    # reject exposure if, for any imfiles, the mean residual flux
    # deviates from the expected value by more than N sigma, (sigma =
    # total pixel variance).  this test is sensible for images which
    # should have a predictable nominal residual flux value (eg, 0.0
    # for a bias).  in general, use with ADDITIVE components
    if ($reject_imfile_flux > 0) {
	if (abs($flux) > $reject_imfile_flux) {
	    print $logFile "Rejecting exposure based on bad imfile flux for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile flux for $name meets requirements: ";
	}
	print $logFile "$flux vs $reject_imfile_flux\n";
    }  else {
	print $logFile "No rejection on imfile flux for $name\n";
    }

    # reject exposure if, for any imfiles, the total pixel variance is
    # larger than the limit
    if ($reject_imfile_stdev > 0) {
	if ($stdev > $reject_imfile_stdev) {
	    print $logFile "Rejecting exposure based on bad imfile stdev for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile stdev for $name meets requirements: ";
	}
	print $logFile "$stdev vs $reject_imfile_stdev\n";

    } else {
	print $logFile "No rejection on imfile stdev for $name\n";
    }

    # reject exposure if, for any imfiles, the variance of the imfile
    # component means is larger than the limit
    if ($reject_imfile_meanstdev > 0) {
	if ($meanStdevs[$i] > $reject_imfile_meanstdev) {
	    print $logFile "Rejecting exposure based on bad imfile mean stdev for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile mean stdev for $name meets requirements: ";
	}
	print $logFile "$meanStdevs[$i] vs $reject_imfile_meanstdev\n";
    } else {
	print $logFile "No rejection on imfile mean stdev for $name\n";
    }

    # reject exposure if, for any imfiles, the signal-to-noise (ie,
    # the mean counts / total pixel variance) of the imfile component
    # means are less than the limit.  this test is sensible for images
    # which have finite residual flux such as a flat-field image.  
    if ($reject_imfile_sn > 0) {
	if ($mean < $stdev * $reject_imfile_sn) {
	    print $logFile "Rejecting exposure based on bad imfile S/N for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile S/N for $name meets requirements: ";
	}
	print $logFile "mean: $mean vs stdev*SNlimit: " . $stdev * $reject_imfile_sn . "\n";
    } else {
	print $logFile "No rejection on imfile S/N for $name\n";
    }

    # reject exposure if, for any imfiles, the signal-to-noise of the
    # imfile component means, based on the stdev of the binned image
    # is less than the limit.  this test is sensible for images which
    # have finite residual flux such as a flat-field image.
    if ($reject_imfile_bin_stdev > 0) {
	if ($binStdev > $reject_imfile_bin_stdev) {
	    print $logFile "Rejecting exposure based on bad imfile binned stdev for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile binned stdev for $name meets requirements: ";
	}
	print $logFile "$binStdev vs $reject_imfile_bin_stdev\n";
    } else {
	print $logFile "No rejection on imfile binned stdev for $name\n";
    }
    if ($reject_imfile_bin_sn > 0) {
	if ($mean < $binStdev * $reject_imfile_bin_sn) {
	    print $logFile "Rejecting exposure based on bad imfile binned S/N for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile binned S/N for $name meets requirements: ";
	}
	print $logFile "mean: $mean vs binStdev*SNlimit: " . $binStdev * $reject_imfile_bin_sn . "\n";
    } else {
	print $logFile "No rejection on imfile binned S/N for $name\n";
    }
}

# calculate the exposure ensemble statistics
my $meanStats = Statistics::Descriptive::Sparse->new();	# Statistics calculator for means
$meanStats->add_data(@means);
my $fluxStats = Statistics::Descriptive::Sparse->new();	# Statistics calculator for means
$fluxStats->add_data(@fluxes);
my $varianceStats = Statistics::Descriptive::Sparse->new(); # Statistics calculator for variances
$varianceStats->add_data(@variances);
my $binVarianceStats = Statistics::Descriptive::Sparse->new(); # Statistics calculator for variances
$binVarianceStats->add_data(@binVariances);

my $mean = $meanStats->mean();	# Mean of the imfile means
my $flux = $fluxStats->mean();	# Mean of the imfile means
my $meanStdev = $meanStats->standard_deviation(); # Stdev of the imfile means
if (not defined $meanStdev) {
    # this is the case for Nimfile == 1
    $meanStdev = 0;
}
my $stdev = sqrt($varianceStats->mean()); # Root-Mean-Square of the imfile stdevs (root mean of variances)
my $binStdev = sqrt($binVarianceStats->mean()); # Root-Mean-Square of the imfile stdevs (root mean of variances)
my $exp_sn = 0.0;
if ($stdev > 0) { $exp_sn = $mean / $stdev; }

## Reject based on the exposure ensemble stats
# reject if the exposure ensemble mean is deviant
unless ($no_op) {
    print $logFile "Exposure mean $mean, stdev $stdev, mean stdev $meanStdev, exp s/n: $exp_sn\n";

    # reject exposure if the ensemble mean residual counts deviate
    # from the expected value by more than N sigma, (sigma = total
    # pixel variance).  this test is sensible for images which should
    # have a predictable nominal residual mean count value (eg, 0.0
    # for a bias).  in general, use with ADDITIVE components
    if ($reject_exp_mean > 0) {
	if (abs($mean) > $reject_exp_mean * $stdev) {
	    print $logFile "Rejecting exposure based on bad mean counts: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure mean counts meets requirements: ";
	}
	print $logFile "mean: $mean, stdev: $stdev (limit is: $reject_exp_mean\n";
    } else {
	print $logFile "No rejection for exp mean\n";
    }

    # reject exposure if, for any imfiles, the mean residual flux
    # deviates from the expected value by more than N sigma, (sigma =
    # total pixel variance).  this test is sensible for images which
    # should have a predictable nominal residual flux value (eg, 0.0
    # for a bias).  in general, use with ADDITIVE components
    if ($reject_exp_flux > 0) {
	if (abs($flux) > $reject_exp_flux * $stdev) {
	    print $logFile "Rejecting exposure based on bad mean flux: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure mean flux meets requirements: ";
	}
	print $logFile "flux: $flux, stdev: $stdev (limit is: $reject_exp_flux\n";
    } else {
	print $logFile "No rejection for exp mean\n";
    }

    # reject exposure if the total pixel variance is larger than the
    # limit
    if ($reject_exp_stdev > 0) {
	if ($stdev > $reject_exp_stdev) {
	    print $logFile "Rejecting exposure based on bad stdev: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure stdev meets requirements: ";
	}
	print $logFile "$stdev vs $reject_exp_stdev\n";
    } else {
	print $logFile "No rejection for exp stdev\n";
    }

    # reject exposure if the variance of the imfile means is larger
    # than the limit
    if ($reject_exp_meanstdev > 0) {
	if ($meanStdev > $reject_exp_meanstdev) {
	    print $logFile "Rejecting exposure based on bad mean stdev: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure mean stdev meets requirements: ";
	}
	print $logFile "$meanStdev vs $reject_exp_meanstdev\n";
    } else {
	print $logFile "No rejection for exp mean stdev\n";
    }

    # reject if the signal-to-noise is insufficient
    if ($reject_exp_sn > 0) {
	if (abs($mean) < abs($stdev * $reject_exp_sn)) {
	    print $logFile "Rejecting exposure based on poor S/N: \n";
	    $reject = 1;
	} else {
	    print $logFile "Exposure S/N meets requirements: \n";
	}
	print $logFile "signal: $mean vs noise: $stdev (s/n limit is: $reject_exp_sn)\n";
    } else {
	print $logFile "No rejection for exp S/N\n";
    }
    # reject if the exposure ensemble stdev is deviant
    if ($reject_exp_bin_stdev > 0) {
	if ($binStdev > $reject_exp_bin_stdev) {
	    print $logFile "Rejecting exposure based on bad binned stdev: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure binned stdev meets requirements: ";
	}
	print $logFile "$stdev vs $reject_exp_bin_stdev\n";
    } else {
	print $logFile "No rejection for exp binned stdev\n";
    }
    # reject if the signal-to-noise is insufficient
    if ($reject_exp_bin_sn > 0) {
	if (abs($mean) < abs($binStdev * $reject_exp_bin_sn)) {
	    print $logFile "Rejecting exposure based on poor binned S/N: \n";
	    $reject = 1;
	} else {
	    print $logFile "Exposure binned S/N meets requirements: \n";
	}
	print $logFile "signal: $mean vs noise: $binStdev (s/n limit is: $reject_exp_bin_sn)\n";
    } else {
	print $logFile "No rejection for exp binned S/N\n";
    }

    close $logFile;
}

# Add the result into the database
my $bg = $mean;
my $bg_stdev = $stdev;
my $bg_mean_stdev = $meanStdev;
my $bin_stdev = $binStdev;

unless ($no_update) {
    my $command = "$dettool -addresidexp -det_id $det_id -iteration $iter -exp_tag $exp_tag";
    $command .= " -recip $recipe1,$recipe2 -path_base $outputRoot ";
    $command .= " -bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_stdev -bin_stdev $bin_stdev";
    $command .= ' -reject' if $reject;
    $command .= " -dbname $dbname" if defined $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	warn("Unable to perform dettool -addresidexp: $error_code\n");
	exit($error_code);
    }
}

END {
    my $status = $?;
    system("sync") == 0
        or die "failed to execute sync: $!" ;
    $? = $status;
}


sub my_die
{
    my $msg = shift; # Warning message on die
    my $det_id = shift;		# Detrend identifier
    my $iter = shift;		# Iteration
    my $exp_tag = shift; # Exposure tag
    my $exit_code = shift; # Exit code to add

    carp($msg);
    if ($det_id and $iter and $exp_tag and not $no_update) {
	my $command = "$dettool -addresidexp -det_id $det_id -iteration $iter -exp_tag $exp_tag -code $exit_code";
	$command .= " -dbname $dbname" if defined $dbname;
###        system ($command);
    }
    exit $exit_code;
}


# Retrieve the requested rejection limit, dying if not extant
sub rejection_limit
{
    my $name = shift;		# Rejection limit to 
    my $type = shift;		# Type of exposure
    my $filter = shift;		# Filter

    my $value = $ipprc->rejection( $name, $det_type, $filter );
    if (not defined $value) {
	$filter = "(no filter)" if not defined $filter;
	die "Unable to determine $name rejection limit for $det_type with $filter.\n";
    }

    return $value;
}




__END__

####

## this function is not well though out.  it loads a collection of
## values (background mean and stdev) for a collection of imfile
## subcomponents.  it then measures the mean background, the
## background stdev (rms of ensemble stdevs), and the background mean
## stdev (rms of the means).  it then tries to reject based on the
## following criteria:
## (background / stdev > limit) for a single component
##    ---> this will ACCEPT for a poor images (large stdev)
## (stdev > limit)
## (mean background / stdev > limit) same problem
## (mean stdev > limit)

### I would suggest the following:
## 1) calculate the ensemble mean and stdev
## 2) for each component, is the (back - mean) / mean stdev > limit?
##    (ie, is it an outlier?)
## 3) is the component stdev > limit? (absolute test)
## 4) calculate the background stdev for the ensemble (excluding rejects)
## 5) is the mean stdev > limit (poor images)
## 6) calculate the ensemble stdev (rms) of remaining (excluding rejects)
## 7) is the ensemble stdev > limit 

## for flats, the value used for stdev should be the fractional stdev
## (stdev/mean) and no rejection should be performed on the basis of
## the mean value, but could still be done on the mean stdev

## the same logical cuts above can be applied to components in an
## imfile, imfiles in an exposure, and exposures in a stack

### this function needs to avoid div by zero: compare Signal vs Noise*limit
