#!/usr/bin/perl

# Write IRAF script to remove cosmic rays using LaCosmic
# Run this on the flat-fielded images which have not yet
# been sky-subtracted! If they -have- been sky subtracted,
# be sure to specify roughly what the sky -was-.

# This will output cr* files which we don't want to use. It's
# better to keep using the ss* files in cooperation with the 
# msk* files.

# History
#  2008Apr22  MM  created
#  2008Jun27  MM  added default bad pixel masks for OLD camera!
#  2008Aug04  MM  added default bad pixel masks for NEW camera!

use Getopt::Long;
use Text::Wrap;

#
# Detailed help message
#
@usage = ("v1.0  MM  22Apr2008\n\nUsage: imacscr (OBJECTS) [--help] [--sigclip=<num>] [--objlim=<num>] [--niter=<num>] [--sky=<num>]\n\n");
@help = (
	 "---------------\n ",
	 "REQUIRED INPUTS\n ",
	 "---------------\n ",
	 "OBJECTS is a file containing all of the science exposures,\n",
	 "one per line, which require cosmic ray removal.\n",
	 "e.g.\n",
	 "fccd0001\n",
	 "fccd0002\n",
	 "fccd0003\n",
	 "...\n",
	 "------\n ",
	 "OUTPUT\n ",
 	 "------\n ",
	 "The output is an IRAF CL script named 'crremove.cl'; run\n",
	 "this file at the cl> prompt with the following syntax:\n",
	 "cl> cl < crremove.cl\n",
	 "The IRAF script returns images prepended by 'cr' \n",
	 "and masks prepended by 'msk'. We should not use the\n",
	 "files prepended with cr for the next step - they are\n",
	 "for visually inspecting the effectiveness of LA Cosmic.\n",
	 );
@switches = (
	     "\t--------\n ",
	     "\tSWITCHES\n ",
	     "\t--------\n ",
	     "\t--sigclip=<num> : detection limit for cosmic rays (sigma) \n",
	     "\t                  (default = 6.0)\n",	 
	     "\t--objlim=<num>  : contrast limit between CR and underlying \n",
	     "\t                   object (default = 5.0)\n",
	     "\t--niter=<num>   : number of iterations to perform \n",
	     "\t                  (default = 4)\n",
	     "\t--sky=<num>     : rough value of the sky before subtraction\n",
	     "\t                  if not subtracted, skip this.\n",
	     "\t                  (default=200)\n",
	 );

#
# Check command-line options
#
if ($#ARGV lt 1) {
    if ($#ARGV eq 0) {
	if ($ARGV[0] eq "--help") {
	    print @usage;
	    print fill ("\t","",@help);
	    print "\n";
	    print @switches;
	    print "\n\n";
	    exit;
	}
    } else {
	die "@usage\For detailed help: imacscr --help\n\n";
    }
}

$list = '';

$sigclip = 6.0;
$niter = 4;
$objlim=5.0;
$skyval=0.0;
GetOptions ('sigclip=f' => \$sigclip,
	    'niter=i' => \$niter,
	    'objlim=f' => \$objlim,
	    'sky=f' => \$skyval);

#
# Misc. variable definitions
#

#
# Open input files
#
if (-e $ARGV[0]) {
    open SCOBJ,$ARGV[0];
    @scobj = <SCOBJ>;
    close SCOBJ;
    chomp @scobj
} else {
    die "  Exiting(1): Can't find file $ARGV[0].\n";
}


#
# Initialize arrays to hold IRAF commands
#

$ladir = `pwd`;
chomp $ladir;

@crr = ("stsdas\n",
	"task lacos_im = $ladir/lacos_im.cl\n",
	"lacos_im.gain=0.83\n",
	"lacos_im.readn=3.30\n",
	"lacos_im.sigclip=$sigclip\n",
	"lacos_im.niter=$niter\n",
	"lacos_im.objlim=$objlim\n",
	"lacos_im.sigfrac=0.3\n",
	"lacos_im.skyval=$skyval\n",
	);


#
# Create processing commands for cosmic ray removal
#
foreach (@scobj) {
    if (-e $_."c1.fits") {
	for $i (1..8) {
	    $img = $_."c$i.fits";
	    $crimg = "cr$img";
	    $cmask = "msk$img";

	    push @crr, "lacos_im $img $crimg $cmask\n";
	}
    } else {
	die "  Exiting(2): Can't find file $_"."c1.fits.\n";
    }
}

########################################################
#
# Create known bad pixel regions
#
########################################################
@bp=();
push @bp, "1499 1499 1 4096\n";
unlink <badpix.c1>; # remove old scripts first
open OUT, ">badpix.c1";
print OUT @bp;
close OUT;

@bp=();
push @bp, "1029 1029 2500 2800\n";
unlink <badpix.c2>; # remove old scripts first
open OUT, ">badpix.c2";
print OUT @bp;
close OUT;

@bp=();
push @bp, "682 682 1 4096\n";
unlink <badpix.c3>; # remove old scripts first
open OUT, ">badpix.c3";
print OUT @bp;
close OUT;

@bp=();
push @bp, "1145 1145 1 4096\n";
unlink <badpix.c4>; # remove old scripts first
open OUT, ">badpix.c4";
print OUT @bp;
close OUT;

@bp=();
unlink <badpix.c5>; # remove old scripts first
open OUT, ">badpix.c5";
print OUT @bp;
close OUT;

@bp=();
push @bp, "686 687 1 4096\n";
unlink <badpix.c6>; # remove old scripts first
open OUT, ">badpix.c6";
print OUT @bp;
close OUT;

@bp=();
push @bp, "810 811 1300 1700\n";
unlink <badpix.c7>; # remove old scripts first
open OUT, ">badpix.c7";
print OUT @bp;
close OUT;

@bp=();
unlink <badpix.c8>; # remove old scripts first
open OUT, ">badpix.c8";
print OUT @bp;
close OUT;

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

# Now combine with lacos masks #
push @crr, "bye\n";
push @crr, "noao\n";
push @crr, "imred\n";
push @crr, "ccdred\n";
push @crr, "del temp.fits\n";
foreach (@scobj) {
    if (-e $_."c1.fits") {
	for $i (1..8) {
	    $img = $_."c$i";
	    
	    # Create new bad pixel mask #
	    push @crr, "badpiximage badpix.c$i $img temp badvalue=1 goodvalue=0 \n";
	    # Combine with lacos mask #
	    push @crr, "imarith msk$img max temp mskss$img\n";
	    push @crr, "del temp.fits\n";
	    
	}
    } else {
	die "  Exiting(2): Can't find file $_"."c1.fits.\n";
    }
}


#
# Print to CL script
#

unlink <crremove.cl>; # remove old scripts first
open OUT, ">crremove.cl";
print OUT @crr;
close OUT;
#
print fill("\t","",("Now enter IRAF and run 'crremove.cl':\n cl> cl < crremove.cl\n "));
print "\n";

#######################
# @array = PARSE($line)
# Parse line of data into an array
# Assumes data separator is whitespace
# ??/??/02  DSR  created
# 09/04/02  DSR  changed "if" statement to "while"
# 08/04/03  DSR  removed $line variable
#######################

sub parse {
    my(@parsed);
    @parsed = split(/\s+/,$_[0]);
    chomp(@parsed);
    #remove whitespace at beginning of line, if any
    while ($parsed[0] eq "") {shift(@parsed)}
    return(@parsed);
}

##########################
# @array = PARSECOM($line)
# Parse by commas
# 08feb11  DSNR  created
##########################

sub parsecom {
    my(@parsed);
    @parsed = split(/,+/,$_[0]);
    chomp(@parsed);
    #remove whitespace at beginning of line, if any
    while ($parsed[0] eq "") {shift(@parsed)}
    return(@parsed);
}

##############################################
# $are_equal = COMPARE_ARRAYS(\@frogs,\@toads)
# Test whether two arrays are the same.
# Copied from http://perl.active-venture.com/pod/perlfaq4-dataarrays.html
# 08feb13  DSNR  copied
##############################################

sub compare_arrays {
    my ($first, $second) = @_;
    no warnings;  # silence spurious -w undef complaints
    return 0 unless @$first == @$second; # compare number of elements
    for (my $i = 0; $i < @$first; $i++) {
	return 0 if $first->[$i] ne $second->[$i];
    }
    return 1;
}
