IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Changeset 42299


Ignore:
Timestamp:
Oct 24, 2022, 1:54:32 PM (4 years ago)
Author:
tdeboer
Message:

merging in change adding extra desperate diff security

File:
1 edited

Legend:

Unmodified
Added
Removed
  • tags/ipp-ps1-20210708/ippScripts/scripts/nightly_science.pl

    r41463 r42299  
    142142my %unique_filter_hash = ();
    143143
     144#set up the camera config
     145my $ipprcam = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up camera", $PS_EXIT_CONFIG_ERROR ); # IPP camera configuration
     146
    144147# Grab the configuration data.
    145148my $conf_cmd = "$ppConfigDump -camera $camera -dump-recipe NIGHTLY_SCIENCE -";
     
    155158foreach my $entry (@{ $metadata }) {
    156159    if (@{ $entry }{name} eq 'CLEAN_MODES') {
    157         my @mode_data = @{ ${ $entry }{value} };
    158         my $this_mode = '';
    159         foreach my $mentry (@mode_data) {
    160             if (${ $mentry }{name} eq 'MODE') {
    161                 $this_mode = ${ $mentry }{value};
    162             }
    163             elsif (${ $mentry }{name} eq 'COMMAND') {
    164                 $clean_config{$this_mode}{COMMAND} = ${ $mentry }{value};
    165             }
    166             elsif (${ $mentry }{name} eq 'RETENTION_TIME') {
    167                 $clean_config{$this_mode}{RETENTION_TIME} = ${ $mentry }{value};
    168             }
    169         }
     160        my @mode_data = @{ ${ $entry }{value} };
     161        my $this_mode = '';
     162        foreach my $mentry (@mode_data) {
     163            if (${ $mentry }{name} eq 'MODE') {
     164                $this_mode = ${ $mentry }{value};
     165            }
     166            elsif (${ $mentry }{name} eq 'COMMAND') {
     167                $clean_config{$this_mode}{COMMAND} = ${ $mentry }{value};
     168            }
     169            elsif (${ $mentry }{name} eq 'RETENTION_TIME') {
     170                $clean_config{$this_mode}{RETENTION_TIME} = ${ $mentry }{value};
     171            }
     172        }
    170173    }
    171174    elsif (${ $entry }{name} eq 'FILTERS') {
    172         $unique_filter_hash{ ${ $entry }{value} } = 1;
     175        $unique_filter_hash{ ${ $entry }{value} } = 1;
    173176#        push @filter_list, ${ $entry }{value};
    174177    }
     
    177180    }
    178181    elsif (${ $entry }{name} eq 'MACRO_DEFINITIONS') {
    179         my @macro_data = @{ ${ $entry }{value} };
    180         my $this_mode = '';
    181         foreach my $mentry (@macro_data) {
    182             if (${ $mentry }{name} eq 'PROC_MODE') {
    183                 $this_mode = ${ $mentry }{value};
    184             }
    185             elsif (${ $mentry }{name} eq 'MACRO') {
    186                 $macro_config{$this_mode} = ${ $mentry }{value};
    187             }
    188         }
     182        my @macro_data = @{ ${ $entry }{value} };
     183        my $this_mode = '';
     184        foreach my $mentry (@macro_data) {
     185            if (${ $mentry }{name} eq 'PROC_MODE') {
     186                $this_mode = ${ $mentry }{value};
     187            }
     188            elsif (${ $mentry }{name} eq 'MACRO') {
     189                $macro_config{$this_mode} = ${ $mentry }{value};
     190            }
     191        }
    189192    }
    190193    elsif (${ $entry }{name} eq 'TARGETS') {
     
    194197            if (${ $tentry }{name} eq 'NAME') {
    195198                $this_target = ${ $tentry }{value};
    196                 $science_config{$this_target}{DISTRIBUTION} = $this_target; # Set the default dist_group
    197             }
    198             else {
    199                 $science_config{$this_target}{ ${ $tentry }{name} } = ${ $tentry }{value};
    200             }
     199                $science_config{$this_target}{DISTRIBUTION} = $this_target; # Set the default dist_group
     200            }
     201            else {
     202                $science_config{$this_target}{ ${ $tentry }{name} } = ${ $tentry }{value};
     203            }
    201204        }
    202205    }
    203206    elsif (${ $entry }{name} eq 'DETRENDS') {
    204         my @detrend_data = @{ ${ $entry }{value} };
    205         my $this_detrend = '';
    206         foreach my $dentry (@detrend_data) {
    207             if (${ $dentry }{name} eq 'NAME') {
    208                 $this_detrend = ${ $dentry }{value};
    209             }
    210             else {
    211                 $detrend_config{$this_detrend}{ ${ $dentry }{name} } = ${ $dentry }{value};
    212             }
    213         }
    214     }           
     207        my @detrend_data = @{ ${ $entry }{value} };
     208        my $this_detrend = '';
     209        foreach my $dentry (@detrend_data) {
     210            if (${ $dentry }{name} eq 'NAME') {
     211                $this_detrend = ${ $dentry }{value};
     212            }
     213            else {
     214                $detrend_config{$this_detrend}{ ${ $dentry }{name} } = ${ $dentry }{value};
     215            }
     216        }
     217    }           
    215218    elsif (${ $entry }{name} eq 'END_OF_NIGHT') {
    216         my @eon_data = @{ ${ $entry }{value} };
    217         my $this_eon = '';
    218         foreach my $tentry (@eon_data) {
    219             if (${ $tentry }{name} eq 'NAME') {
    220                 $this_eon = ${ $tentry }{value};
    221             }
    222             else {
    223                 $eon_config{$this_eon}{ ${ $tentry }{name} } = ${ $tentry }{value};
    224             }
    225         }
     219        my @eon_data = @{ ${ $entry }{value} };
     220        my $this_eon = '';
     221        foreach my $tentry (@eon_data) {
     222            if (${ $tentry }{name} eq 'NAME') {
     223                $this_eon = ${ $tentry }{value};
     224            }
     225            else {
     226                $eon_config{$this_eon}{ ${ $tentry }{name} } = ${ $tentry }{value};
     227            }
     228        }
    226229    }
    227230}
     
    231234    my $time;
    232235    if ($date =~ / /) {
    233         ($date,$time) = split / /, $date;
     236        ($date,$time) = split / /, $date;
    234237    }
    235238    elsif ($date =~ /T/) {
    236         ($date,$time) = split /T/, $date;
     239        ($date,$time) = split /T/, $date;
    237240    }
    238241    my ($year,$month,$day) = split /-/, $date;
    239242    if (defined($time)) {
    240         my ($hour,$min,$sec) = split /\:/, $time; #/;
    241         $datetime = DateTime->new( year => $year,
    242                                    month => $month,
    243                                    day => $day,
    244                                    hour => $hour,
    245                                    min => $min,
    246                                    second => $sec,
    247                                    time_zone => 'UTC');
     243        my ($hour,$min,$sec) = split /\:/, $time; #/;
     244        $datetime = DateTime->new( year => $year,
     245                                   month => $month,
     246                                   day => $day,
     247                                   hour => $hour,
     248                                   min => $min,
     249                                   second => $sec,
     250                                   time_zone => 'UTC');
    248251    }
    249252    else {
    250         $datetime = DateTime->now(time_zone => 'UTC');
    251         $datetime->set_year($year);
    252         $datetime->set_day($day);
    253         $datetime->set_month($month);
    254     }
    255 }    
     253        $datetime = DateTime->now(time_zone => 'UTC');
     254        $datetime->set_year($year);
     255        $datetime->set_day($day);
     256        $datetime->set_month($month);
     257    }
     258}   
    256259else {
    257260    $datetime = DateTime->now(time_zone => 'UTC'); # time_zone   => 'Pacific/Honolulu');
     
    263266    foreach my $t (keys %science_config) {
    264267        if ($t ne $this_target_only) {
    265             undef($science_config{$t});
     268            undef($science_config{$t});
    266269        }
    267270    }
     
    282285    foreach my $t (keys %clean_config) {
    283286        if ($t ne $this_mode_only) {
    284             undef($clean_config{$t});
     287            undef($clean_config{$t});
    285288        }
    286289    }
     
    295298
    296299if (defined($desdiffdt) == 0) {
    297         $desdiffdt = 1.5;
     300        $desdiffdt = 1.5;
    298301}
    299302
    300303#Build in a safety for desdiffdt
    301304if ((defined($desdiffdt) == 1) && ($desdiffdt <= 0.5)) {
    302         $desdiffdt = 0.5;
     305        $desdiffdt = 0.5;
    303306}
    304307
     
    312315    my $v;
    313316    foreach $z (sort (keys %science_config)) {
    314         foreach $v (keys %{ $science_config{$z} }) {
    315             print "SCIENCE: $z $v $science_config{$z}{$v}\n";
    316         }
     317        foreach $v (keys %{ $science_config{$z} }) {
     318            print "SCIENCE: $z $v $science_config{$z}{$v}\n";
     319        }
    317320    }
    318321    foreach $z (sort (keys %detrend_config)) {
    319         foreach $v (keys %{ $detrend_config{$z} }) {
    320             print "DETREND: $z $v $detrend_config{$z}{$v}\n";
    321         }
     322        foreach $v (keys %{ $detrend_config{$z} }) {
     323            print "DETREND: $z $v $detrend_config{$z}{$v}\n";
     324        }
    322325    }
    323326    foreach $z (keys (%clean_config)) {
    324         foreach $v (keys %{ $clean_config{$z} }) {
    325             print "CLEAN: $z $v $clean_config{$z}{$v}\n";
    326         }
     327        foreach $v (keys %{ $clean_config{$z} }) {
     328            print "CLEAN: $z $v $clean_config{$z}{$v}\n";
     329        }
    327330    }
    328331    foreach $z (@filter_list) {
    329         print "FILTER: $z\n";
     332        print "FILTER: $z\n";
    330333    }
    331334    foreach $z (keys (%macro_config)) {
    332         print "MACROS: $z $macro_config{$z}\n";
     335        print "MACROS: $z $macro_config{$z}\n";
    333336    }
    334337}
     
    397400    &execute_stacks($date,$metadata_out{nsObservingState});
    398401    if ($metadata_out{nsStackState} eq 'QUEUESTACKING') {
    399         $metadata_out{nsStackState} = 'STACKING_POSSIBLE_ERROR';
     402        $metadata_out{nsStackState} = 'STACKING_POSSIBLE_ERROR';
    400403    }
    401404    return_metadata($date);
     
    416419    &execute_diffs($date,$metadata_out{nsObservingState});
    417420    if ($metadata_out{nsDiffState} eq 'QUEUESTACKING') {
    418         $metadata_out{nsDiffState} = 'STACKING_POSSIBLE_ERROR';
     421        $metadata_out{nsDiffState} = 'STACKING_POSSIBLE_ERROR';
    419422    }
    420423    return_metadata($date);
     
    481484        my ($exp_name,$registered,$dateobs,$imfiles,$summit_fault,
    482485            $download_state,$download_count,$new_state,$exp_id,$exp_type) = @{ $row_ref };
    483         $Nsummit_imfiles += $imfiles;
    484         $Ndownload_imfiles += $download_count;
     486        $Nsummit_imfiles += $imfiles;
     487        $Ndownload_imfiles += $download_count;
    485488        $Nsummit_exps++;
    486489        if ($summit_fault) {
    487             print STDERR "check_summit_copy: $date $exp_name has summit_fault $summit_fault";
     490            print STDERR "check_summit_copy: $date $exp_name has summit_fault $summit_fault";
    488491            if (($exp_type ne 'OBJECT')||($exp_name =~ /^c.*/)) {
    489492                print STDERR " (but I don't care).\n";
     
    526529    }
    527530    elsif ($Ndownload_imfiles != $Nsummit_imfiles) {
    528         print STDERR "Not done downloading from the summit for $date (Summit: $Nsummit_imfiles, Downloaded: $Ndownload_imfiles)\n";
    529         $metadata_out{nsRegState} = 'NEW';
     531        print STDERR "Not done downloading from the summit for $date (Summit: $Nsummit_imfiles, Downloaded: $Ndownload_imfiles)\n";
     532        $metadata_out{nsRegState} = 'NEW';
    530533    }
    531534    else {
     
    615618    }
    616619    if (defined($reduction)) {
    617         $cmd .= " -set_reduction $reduction ";
     620        $cmd .= " -set_reduction $reduction ";
    618621    }
    619622    $cmd .= " $select ";
     
    674677
    675678    foreach my $target (sort (keys %science_config)) {
    676         my ($Nexposures,$Nimfiles,$Nburntooled,$Nalready) = check_chip_status($date,$target);
    677         print "BTSTATS: $date $target $Nexposures $Nimfiles $Nburntooled $Nalready\n";
     679        my ($Nexposures,$Nimfiles,$Nburntooled,$Nalready) = check_chip_status($date,$target);
     680        print "BTSTATS: $date $target $Nexposures $Nimfiles $Nburntooled $Nalready\n";
    678681    }
    679682}
     
    695698    $cmd .= " -set_label dqstats.nightlyscience ";
    696699    if ($debug == 1) {
    697         $cmd .= ' -pretend ';
     700        $cmd .= ' -pretend ';
    698701    }
    699702    print STDERR "$cmd\n";
     
    703706sub pre_dqstats_queue {
    704707    my $date = shift;
    705     
     708   
    706709    my $command = construct_dqstats_cmd($date) . ' -pretend ';
    707710    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     
    711714        &my_die("Unable to perform dqstatstool: $error_code",1,1,,$date, $PS_EXIT_SYS_ERROR);
    712715    }
    713     
     716   
    714717    my @input_exposures = split /\n/, (join '', @$stdout_buf);
    715718
     
    735738    my ($Nexposures,$Nchips,$Ncams) = pre_dqstats_queue($date);
    736739    if ($Nexposures == 0) {
    737         print STDERR "execute_dqstats: No exposures on date $date.\n";
     740        print STDERR "execute_dqstats: No exposures on date $date.\n";
    738741    }
    739742    elsif ($Ncams != $Nchips) {
    740         print STDERR "execute_dqstats: Not done processing data through camera stage.\n";
     743        print STDERR "execute_dqstats: Not done processing data through camera stage.\n";
    741744    }
    742745    else {
    743         unless(defined($pretend)) {
    744             dqstats_queue($date);
    745         }
    746         if (defined($pretend)) {
    747             add_to_macro_list('check_dqstats',1,$date);
    748         }
    749         else {
    750             add_to_macro_list('queue_dqstats',1,$date);
    751         }
     746        unless(defined($pretend)) {
     747            dqstats_queue($date);
     748        }
     749        if (defined($pretend)) {
     750            add_to_macro_list('check_dqstats',1,$date);
     751        }
     752        else {
     753            add_to_macro_list('queue_dqstats',1,$date);
     754        }
    752755    }
    753756}   
     
    761764
    762765    my ($label,$workdir,$filter,$exp_type,$det_type,$ref_det_id,$ref_iter,$maxN) = get_dettool_parameters($date,$target);
    763     
     766   
    764767    my $select = "-select_dateobs_begin ${date}T00:00:00 -select_dateobs_end ${date}T23:59:59 ";
    765768    my $use_limits = " -use_begin ${date}T00:00:00 -use_end ${date}T23:59:59 ";
     
    778781    $cmd .= " $use_limits ";
    779782    if ($maxN > 0) {
    780         $cmd .= " -random_subset -random_limit $maxN ";
     783        $cmd .= " -random_subset -random_limit $maxN ";
    781784    }
    782785    if ($debug == 1) {
    783         $cmd .= ' -pretend ';
     786        $cmd .= ' -pretend ';
    784787    }
    785788    print STDERR "$cmd\n";
    786789    return($cmd);
    787 }    
     790}   
    788791
    789792sub verify_uniqueness_detverify {
     
    792795
    793796    my ($label,$workdir,$filter,$exp_type,$det_type,$ref_det_id,$ref_iter,$maxN) = get_dettool_parameters($date,$target);
    794     
     797   
    795798    my $db = init_gpc_db();
    796799    my $sth = "SELECT * FROM detRun WHERE workdir = '$workdir' AND ref_det_id = $ref_det_id AND ref_iter = $ref_iter";
     
    803806    my $date = shift;
    804807    my $target = shift;
    805     
     808   
    806809    my $command = construct_dettool_cmd($date,$target) . ' -pretend ';
    807810    my ($success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    808         run ( command => $command, verbose => $verbose);
     811        run ( command => $command, verbose => $verbose);
    809812    unless ($success) {
    810         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    811         &my_die("Unable to perform dettool: $error_code", 0,0, $date, $PS_EXIT_SYS_ERROR);
    812     }
    813     
     813        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     814        &my_die("Unable to perform dettool: $error_code", 0,0, $date, $PS_EXIT_SYS_ERROR);
     815    }
     816   
    814817    my @input_exposures = split /\n/, (join '', @$stdout_buf);
    815818    return($#input_exposures + 1);
     
    819822    my $date = shift;
    820823    my $target = shift;
    821     
     824   
    822825    my $command = construct_dettool_cmd($date,$target);
    823826    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    824         run ( command => $command, verbose => $verbose);
     827        run ( command => $command, verbose => $verbose);
    825828    unless ($success) {
    826         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    827         &my_die("Unable to perform chiptool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     829        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     830        &my_die("Unable to perform chiptool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    828831    }
    829832    $metadata_out{nsDetState} = 'DETREND_QUEUED';
     
    836839    my $exposures = 0;
    837840    foreach my $target (sort (keys %detrend_config)) {
    838         my ($Nexposures) = pre_detrend_queue($date,$target);
    839         if ($Nexposures == 0) {
    840             print STDERR "execute_detrends: Target $target on $date had no exposures.\n";
    841             next;
    842         }
    843         $exposures++;
    844         unless(defined($pretend)) {
    845             detrend_queue($date,$target);
    846         }
    847         if (defined($pretend)) {
    848             add_to_macro_list('check_detrends',1,$date,$target,"dettool");
    849         }
    850         else {
    851             add_to_macro_list('queue_detrends',1,$date,$target,"dettool");
    852         }
     841        my ($Nexposures) = pre_detrend_queue($date,$target);
     842        if ($Nexposures == 0) {
     843            print STDERR "execute_detrends: Target $target on $date had no exposures.\n";
     844            next;
     845        }
     846        $exposures++;
     847        unless(defined($pretend)) {
     848            detrend_queue($date,$target);
     849        }
     850        if (defined($pretend)) {
     851            add_to_macro_list('check_detrends',1,$date,$target,"dettool");
     852        }
     853        else {
     854            add_to_macro_list('queue_detrends',1,$date,$target,"dettool");
     855        }
    853856    }
    854857    if ($exposures == 0) {
    855         $metadata_out{nsDetState} = 'DETREND_DROP';
     858        $metadata_out{nsDetState} = 'DETREND_DROP';
    856859    }
    857860    if (($metadata_out{nsDetState} eq 'CHECKDETRENDS') && ($exposures > 0)) {
    858         $metadata_out{nsDetState} eq 'QUEUEDETRENDS';
     861        $metadata_out{nsDetState} eq 'QUEUEDETRENDS';
    859862    }
    860863}
     
    882885#     $cmd .= " $select ";
    883886#     if ($debug == 1) {
    884 #       $cmd .= ' -pretend ';
     887#       $cmd .= ' -pretend ';
    885888#     }
    886889#     print STDERR "$cmd\n";
     
    895898
    896899    my $dt = DateTime->new(year => $year, month => $month, day => $day,
    897                            hour => 0, minute => 0, second => 0, nanosecond => 0,
    898                            time_zone => 'Pacific/Honolulu');
     900                           hour => 0, minute => 0, second => 0, nanosecond => 0,
     901                           time_zone => 'Pacific/Honolulu');
    899902    do {
    900         $dt->add(days => 1);
    901         my $ymd = $dt->ymd;
    902         my $md_cmd = "moondata $ymd 0 0";
    903         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    904             run ( command => $md_cmd, verbose => $verbose);
    905         unless ($success) {
    906             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    907             &my_die("Unable to perform moondata: $error_code", 0,0, $date, $PS_EXIT_SYS_ERROR);
    908         }
    909         my @result = split /\s+/,(join "\n", @$stdout_buf);
    910         if (abs($result[6]) <= 0.6) {
    911             $dateobs_end = $ymd;
    912         }
     903        $dt->add(days => 1);
     904        my $ymd = $dt->ymd;
     905        my $md_cmd = "moondata $ymd 0 0";
     906        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     907            run ( command => $md_cmd, verbose => $verbose);
     908        unless ($success) {
     909            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     910            &my_die("Unable to perform moondata: $error_code", 0,0, $date, $PS_EXIT_SYS_ERROR);
     911        }
     912        my @result = split /\s+/,(join "\n", @$stdout_buf);
     913        if (abs($result[6]) <= 0.6) {
     914            $dateobs_end = $ymd;
     915        }
    913916    } while (!defined($dateobs_end));
    914     
     917   
    915918    do {
    916         $dt->subtract(days => 1);
    917         my $ymd = $dt->ymd;
    918         my $md_cmd = "moondata $ymd 0 0";
    919         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    920             run ( command => $md_cmd, verbose => $verbose);
    921         unless ($success) {
    922             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    923             &my_die("Unable to perform moondata: $error_code", 0,0, $date, $PS_EXIT_SYS_ERROR);
    924         }
    925         my @result = split /\s+/,(join "", @$stdout_buf);
    926         if (abs($result[6]) <= 0.6) {
    927             $dateobs_begin = $ymd;
    928         }
     919        $dt->subtract(days => 1);
     920        my $ymd = $dt->ymd;
     921        my $md_cmd = "moondata $ymd 0 0";
     922        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     923            run ( command => $md_cmd, verbose => $verbose);
     924        unless ($success) {
     925            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     926            &my_die("Unable to perform moondata: $error_code", 0,0, $date, $PS_EXIT_SYS_ERROR);
     927        }
     928        my @result = split /\s+/,(join "", @$stdout_buf);
     929        if (abs($result[6]) <= 0.6) {
     930            $dateobs_begin = $ymd;
     931        }
    929932    } while (!defined($dateobs_begin));
    930        
     933       
    931934    return($dateobs_begin,$dateobs_end);
    932935}
    933936
    934 # sub pre_sweetspot_queue { 
     937# sub pre_sweetspot_queue {
    935938#     my $date = shift;
    936939#     my $command = construct_sweetspot_cmd($date) . ' -pretend ';
    937940#     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    938 #       run ( command => $command, verbose => $verbose );
     941#       run ( command => $command, verbose => $verbose );
    939942#     unless ($success) {
    940943#         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     
    943946#     my @stacks = split /\n/, (join '', @$stdout_buf);
    944947#     my $Nstacks = $#stacks + 1;
    945         
     948       
    946949#     return(1,$Nstacks);
    947950# }
     
    951954#     my $command = construct_sweetspot_cmd($date);
    952955#     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    953 #       run ( command => $command, verbose => $verbose );
     956#       run ( command => $command, verbose => $verbose );
    954957#     unless ($success) {
    955958#         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     
    958961#     my @stacks = split /\n/, (join '', @$stdout_buf);
    959962#     my $Nstacks = $#stacks + 1;
    960     
     963   
    961964#     return(1,$Nstacks);
    962965# }
    963966
    964 # sub execute_sweetspot {    
     967# sub execute_sweetspot {   
    965968#     my $date = shift;
    966969#     my $pretend = shift;
    967     
     970   
    968971#     my ($is_lunation_date,$Nstacks) = pre_sweetspot_queue($date);
    969972#     if ($Nstacks == 0) {
    970 #       print STDERR "execute_sweetspot: No new stacks to make ($Nstacks)\n";
    971 #       $metadata_out{nsSSState} = 'SS_EMPTY';
    972 #       return();
     973#       print STDERR "execute_sweetspot: No new stacks to make ($Nstacks)\n";
     974#       $metadata_out{nsSSState} = 'SS_EMPTY';
     975#       return();
    973976#     }
    974977#     if ($Nstacks < 10) {
    975 #       print STDERR "execute_sweetspot: Too few new stacks to make ($Nstacks)\n";
    976 #       $metadata_out{nsSSState} = 'SS_FEW';
    977 #       return();
     978#       print STDERR "execute_sweetspot: Too few new stacks to make ($Nstacks)\n";
     979#       $metadata_out{nsSSState} = 'SS_FEW';
     980#       return();
    978981#     }
    979982#     if ($is_lunation_date == 0) {
    980 #       print STDERR "execute_sweetspot: Invalid lunation date. ($date $is_lunation_date)\n";
    981 #       $metadata_out{nsSSState} = 'SS_ERROR';
    982 #       return();
     983#       print STDERR "execute_sweetspot: Invalid lunation date. ($date $is_lunation_date)\n";
     984#       $metadata_out{nsSSState} = 'SS_ERROR';
     985#       return();
    983986#     }
    984987#     $metadata_out{nsSSState} = 'SS_QUEUE';
    985988#     $metadata_out{nsSweetSpot} = $Nstacks;
    986989#     unless(defined($pretend)) {
    987 #       $metadata_out{nsSSState} = 'SS_DONE';
    988 #       sweetspot_queue($date);
     990#       $metadata_out{nsSSState} = 'SS_DONE';
     991#       sweetspot_queue($date);
    989992#     }
    990993#     if (defined($pretend)) {
    991 #       add_to_macro_list('check_sweetspot',1,$date);
     994#       add_to_macro_list('check_sweetspot',1,$date);
    992995#     }
    993996#     else {
    994 #       add_to_macro_list('queue_sweetspot',1,$date);
     997#       add_to_macro_list('queue_sweetspot',1,$date);
    995998#     }
    996999# }
     
    10201023    $cmd .= " -select_good_frac_min 0.05";
    10211024    if (defined($reduction)) {
    1022         $cmd .= " -set_reduction $reduction ";
     1025        $cmd .= " -set_reduction $reduction ";
    10231026    }
    10241027    else {
    1025         $cmd .= " -set_reduction NIGHTLY_STACK ";
     1028        $cmd .= " -set_reduction NIGHTLY_STACK ";
    10261029    }
    10271030    if (defined($science_config{$target}{ADDITIONAL_STACK_LABEL})) {
    1028         # Grab list of skycells
    1029         my $skycell_select = '';
    1030         {
    1031             my %skycells = ();
    1032             my $warpcmd = "$warptool -warped -label $label -data_group $data_group  -dbname $dbname";
    1033             my ($success, $error_code, $full_buf, $stdout_buf, $stderr_buf) =
    1034                 run(command => $warpcmd, verbose => $verbose);
    1035             unless($success) {
    1036                 $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    1037                 &my_die("Unabel to perform warptool -warped to determine skycell_ids: $error_code",$target);
    1038             }
    1039             my $runs = $mdcParser->parse_list(join "", @$stdout_buf) or
    1040                 &my_die("Unabel to parse warptool -warped to determine skycell_ids: $error_code",$target);
    1041             if ($#{ $runs } != -1) {
    1042                 for my $warp (@$runs) {
    1043                     $skycells{$warp->{skycell_id}} = 1;
    1044                 }
    1045                 foreach my $skycell (sort (keys (%skycells))) {
    1046                     $skycell_select .= " -select_skycell_id $skycell ";
    1047                 }
    1048                 $cmd .= " -select_label $science_config{$target}{ADDITIONAL_STACK_LABEL} $skycell_select ";
    1049             }
    1050         }
     1031        # Grab list of skycells
     1032        my $skycell_select = '';
     1033        {
     1034            my %skycells = ();
     1035            my $warpcmd = "$warptool -warped -label $label -data_group $data_group  -dbname $dbname";
     1036            my ($success, $error_code, $full_buf, $stdout_buf, $stderr_buf) =
     1037                run(command => $warpcmd, verbose => $verbose);
     1038            unless($success) {
     1039                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     1040                &my_die("Unabel to perform warptool -warped to determine skycell_ids: $error_code",$target);
     1041            }
     1042            my $runs = $mdcParser->parse_list(join "", @$stdout_buf) or
     1043                &my_die("Unabel to parse warptool -warped to determine skycell_ids: $error_code",$target);
     1044            if ($#{ $runs } != -1) {
     1045                for my $warp (@$runs) {
     1046                    $skycells{$warp->{skycell_id}} = 1;
     1047                }
     1048                foreach my $skycell (sort (keys (%skycells))) {
     1049                    $skycell_select .= " -select_skycell_id $skycell ";
     1050                }
     1051                $cmd .= " -select_label $science_config{$target}{ADDITIONAL_STACK_LABEL} $skycell_select ";
     1052            }
     1053        }
    10511054    }
    10521055    $cmd .= " $select ";
     
    10901093    my $where_possibly_faulted = $where . " AND ( " ;
    10911094    foreach my $acceptable_quality (@unrecoverable_quality) {
    1092         $where_possibly_faulted .= " quality = $acceptable_quality OR ";
     1095        $where_possibly_faulted .= " quality = $acceptable_quality OR ";
    10931096    }
    10941097    $where_possibly_faulted .= " 0 )";
     
    11191122        $Nalready += $trash[0];
    11201123    }
    1121     
     1124   
    11221125    my $minimum_required_warp;
    11231126    if ($observing_state eq 'OBSERVING') {
    1124         $minimum_required_warp = $science_config{$target}{MIN_STACK};
     1127        $minimum_required_warp = $science_config{$target}{MIN_STACK};
    11251128    }
    11261129    unless (defined($minimum_required_warp)) {
    1127         $minimum_required_warp = 0;
     1130        $minimum_required_warp = 0;
    11281131    }
    11291132
     
    11431146        &my_die("Unable to perform stacktool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    11441147    }
    1145     
    1146     
     1148   
     1149   
    11471150    return(0);
    11481151}
     
    11581161    my $is_registering;
    11591162    if ($metadata_out{nsRegistrationState} eq 'REGISTERED') {
    1160         $is_registering = 0;
     1163        $is_registering = 0;
    11611164    }
    11621165    else {
    1163         $is_registering = 1;
     1166        $is_registering = 1;
    11641167    }
    11651168
    11661169    foreach my $target (sort (keys %science_config)) {
    1167         if ($science_config{$target}{STACKABLE} == 1) {
    1168             foreach my $filter (@filter_list) {
     1170        if ($science_config{$target}{STACKABLE} == 1) {
     1171            foreach my $filter (@filter_list) {
    11691172                my ($Nexposures,$NprocChips,$NprocWarps,$NrequiredWarps,$Nalready) = pre_stack_queue($date,$observing_state,$target,$filter);
    11701173                if ((!defined($force_stack_count))&&($NprocChips != $NprocWarps)) { # This makes me sad. :(
    1171                     if ($debug == 1) {
    1172                         print STDERR "execute_stacks: Target $target on $date is not fully processed. ($NprocChips $NprocWarps)\n";
    1173                     }
    1174                     $is_processing = 1;
     1174                    if ($debug == 1) {
     1175                        print STDERR "execute_stacks: Target $target on $date is not fully processed. ($NprocChips $NprocWarps)\n";
     1176                    }
     1177                    $is_processing = 1;
    11751178                    $metadata_out{nsStackState} = 'FORCETOWARP';
    11761179                    next;
    11771180                }
    11781181                if ($Nexposures == 0) {
    1179                     if ($debug == 1) {
    1180                         print STDERR "execute_stacks: Target $target in filter $filter on $date has no exposures.\n";
    1181                     }
     1182                    if ($debug == 1) {
     1183                        print STDERR "execute_stacks: Target $target in filter $filter on $date has no exposures.\n";
     1184                    }
    11821185                    next;
    11831186                }
    1184                 if ($NprocWarps < $NrequiredWarps) {
    1185                     if ($debug == 1) {
    1186                         print STDERR "execute_stacks: Target $target in filter $filter on $date has too few warps to begin stacking. ($NprocWarps $NrequiredWarps)\n";
    1187                     }
    1188                     next;
    1189                 }
    1190                 $Npotential++;
     1187                if ($NprocWarps < $NrequiredWarps) {
     1188                    if ($debug == 1) {
     1189                        print STDERR "execute_stacks: Target $target in filter $filter on $date has too few warps to begin stacking. ($NprocWarps $NrequiredWarps)\n";
     1190                    }
     1191                    next;
     1192                }
     1193                $Npotential++;
    11911194                if ($Nalready != 0) {
    1192                     $Nqueued++;
    1193                     if ($debug == 1) {
    1194                         print STDERR "execute_stacks: Not queueing $target in filter $filter on $date due to already existing stacks.\n";
    1195                     }
    1196                     unless ($metadata_out{nsStackState} eq 'FORCETOWARP') {
    1197                         $metadata_out{nsStackState} = 'STACKING';
    1198                     }
     1195                    $Nqueued++;
     1196                    if ($debug == 1) {
     1197                        print STDERR "execute_stacks: Not queueing $target in filter $filter on $date due to already existing stacks.\n";
     1198                    }
     1199                    unless ($metadata_out{nsStackState} eq 'FORCETOWARP') {
     1200                        $metadata_out{nsStackState} = 'STACKING';
     1201                    }
    11991202                    next;
    12001203                }
     
    12031206                }
    12041207                unless(defined($pretend)) {
    1205                     if ($debug == 1) {
    1206                         print STDERR "execute_stacks: Target $target in filter $filter on $date has exposures and will be queued.\n";
    1207                     }
     1208                    if ($debug == 1) {
     1209                        print STDERR "execute_stacks: Target $target in filter $filter on $date has exposures and will be queued.\n";
     1210                    }
    12081211                    stack_queue($date,$target,$filter);
    1209                     $Nqueued ++;
    1210                 }
    1211                 if (defined($pretend)) {
    1212                     add_to_macro_list('check_stacks',$science_config{$target}{STACKABLE},$date,$target,$filter);
    1213                 }
    1214                 else {
    1215                     add_to_macro_list('queue_stacks',$science_config{$target}{STACKABLE},$date,$target,$filter);
    1216                 }
    1217             }
    1218         }
    1219         else {
    1220             if ($debug == 1) {
    1221                 print STDERR "execute_stacks: Target $target is not auto-stackable.\n";
    1222             }
     1212                    $Nqueued ++;
     1213                }
     1214                if (defined($pretend)) {
     1215                    add_to_macro_list('check_stacks',$science_config{$target}{STACKABLE},$date,$target,$filter);
     1216                }
     1217                else {
     1218                    add_to_macro_list('queue_stacks',$science_config{$target}{STACKABLE},$date,$target,$filter);
     1219                }
     1220            }
     1221        }
     1222        else {
     1223            if ($debug == 1) {
     1224                print STDERR "execute_stacks: Target $target is not auto-stackable.\n";
     1225            }
    12231226        }
    12241227    }
     
    12261229    $metadata_out{nsStackQueued}    = $Nqueued;
    12271230    if (($Npotential == $Nqueued)&&($metadata_out{nsObservingState} eq 'END_OF_NIGHT')&&($is_processing == 0)&&($is_registering == 0)) {
    1228         $metadata_out{nsStackState} = 'FINISHED_STACKS';
    1229     }   
     1231        $metadata_out{nsStackState} = 'FINISHED_STACKS';
     1232    }   
    12301233}
    12311234
     
    12461249    $stack_done_sth .= " AND ((state = 'full') OR (state = 'new' && fault != 0)) ";
    12471250    if ($debug == 1) {
    1248         print STDERR "post_stack_queue: database queries:\n";
    1249         print STDERR "$stack_full_sth\n";
    1250         print STDERR "$stack_done_sth\n";
     1251        print STDERR "post_stack_queue: database queries:\n";
     1252        print STDERR "$stack_full_sth\n";
     1253        print STDERR "$stack_done_sth\n";
    12511254    }
    12521255    my $stack_full_ref = $db->selectall_arrayref( $stack_full_sth );
     
    12591262    my $date = shift;
    12601263    my $pretend = shift;
    1261     
     1264   
    12621265    foreach my $target (sort (keys %science_config)) {
    12631266        if ($science_config{$target}{STACKABLE} == 1) {
    1264             my ($Nstacks, $Nattempted) = post_stack_queue($date,$target);
    1265             if ($debug == 1) {
    1266                 print STDERR "confirm_stacks: Target $target on $date has $Nattempted attempts on $Nstacks.\n";
    1267             }
    1268             if ($Nstacks != $Nattempted) {
    1269                 if ($debug == 1) {
    1270                     print STDERR "confirm_stacks: Target $target on $date is not done stacking. $Nstacks $Nattempted\n";
    1271                 }
    1272                 if ($metadata_out{nsStackState} eq 'CONFIRM_STACKING') {
    1273                     $metadata_out{nsStackState} = 'STACKING';
    1274                 }
    1275                 next;
    1276             }
    1277             if ($Nstacks == 0) {
    1278                 if ($debug == 1) {
    1279                     print STDERR "confirm_stacks: Target $target on $date has no stacks. Skipping.\n";
    1280                 }
    1281                 next;
    1282             }
    1283             if ($metadata_out{nsStackState} eq 'CONFIRM_STACKING') {
    1284                 if (defined($pretend)) {
    1285                     add_to_macro_list('check_confirm_stacks',$science_config{$target}{STACKABLE},$date,$target);
    1286                 }
    1287                 else {
    1288                     add_to_macro_list('confirm_stacks',$science_config{$target}{STACKABLE},$date,$target);
    1289                 }
    1290             }
    1291         }
    1292     }
    1293 }          
     1267            my ($Nstacks, $Nattempted) = post_stack_queue($date,$target);
     1268            if ($debug == 1) {
     1269                print STDERR "confirm_stacks: Target $target on $date has $Nattempted attempts on $Nstacks.\n";
     1270            }
     1271            if ($Nstacks != $Nattempted) {
     1272                if ($debug == 1) {
     1273                    print STDERR "confirm_stacks: Target $target on $date is not done stacking. $Nstacks $Nattempted\n";
     1274                }
     1275                if ($metadata_out{nsStackState} eq 'CONFIRM_STACKING') {
     1276                    $metadata_out{nsStackState} = 'STACKING';
     1277                }
     1278                next;
     1279            }
     1280            if ($Nstacks == 0) {
     1281                if ($debug == 1) {
     1282                    print STDERR "confirm_stacks: Target $target on $date has no stacks. Skipping.\n";
     1283                }
     1284                next;
     1285            }
     1286            if ($metadata_out{nsStackState} eq 'CONFIRM_STACKING') {
     1287                if (defined($pretend)) {
     1288                    add_to_macro_list('check_confirm_stacks',$science_config{$target}{STACKABLE},$date,$target);
     1289                }
     1290                else {
     1291                    add_to_macro_list('confirm_stacks',$science_config{$target}{STACKABLE},$date,$target);
     1292                }
     1293            }
     1294        }
     1295    }
     1296}          
    12941297
    12951298#
     
    13081311
    13091312    my $count = 0;
    1310     
     1313   
    13111314    my $sth = "SELECT DISTINCT diff_id from diffRun JOIN diffInputSkyfile USING(diff_id) where data_group = '$data_group' AND warp1 = $warp_id_1 AND warp2 = $warp_id_2";
    13121315    my $data_ref = $db->selectall_arrayref( $sth );
     
    13311334
    13321335    my $count = 0;
    1333     
     1336   
    13341337    my $sth = "SELECT DISTINCT diff_id from diffRun JOIN diffInputSkyfile USING(diff_id) where (label = '$label' OR label = 'goto_cleaned') AND warp1 = $warp_id_1 AND warp2 = $warp_id_2";
    13351338    my $data_ref = $db->selectall_arrayref( $sth );
     
    13491352    my $filter = shift;
    13501353    my ($label,$workdir,$obs_mode,$object,$comment,$tess_id,$dist_group,$data_group,$reduction) = get_tool_parameters($date,$target);
    1351     
     1354   
    13521355    my $db = init_gpc_db();
    13531356
     
    13581361    my $where_possibly_faulted = $where . " AND ( " ;
    13591362    foreach my $acceptable_quality (@unrecoverable_quality) {
    1360         $where_possibly_faulted .= " quality = $acceptable_quality OR ";
     1363        $where_possibly_faulted .= " quality = $acceptable_quality OR ";
    13611364    }
    13621365    $where_possibly_faulted .= " 0 )";
     
    13831386    my $is_registering;
    13841387    if ($metadata_out{nsRegistrationState} eq 'REGISTERED') {
    1385         $is_registering = 0;
     1388        $is_registering = 0;
    13861389    }
    13871390    else {
    1388         $is_registering = 1;
     1391        $is_registering = 1;
    13891392    }
    13901393
    13911394    foreach my $target (sort (keys %science_config)) {
    1392         if ($science_config{$target}{DIFFABLE} == 1) {
    1393             foreach my $filter (@filter_list) {
    1394                 $Npotential ++;
    1395                 my ($NprocChips,$NprocWarps) = pre_diff_queue($date,$observing_state,$target,$filter);
    1396                 if ((!defined($force_diff_count))&&($NprocChips != $NprocWarps)) {
    1397                     if ($debug == 1) {
    1398                         print STDERR "execute_diffs: Target $target in filter $filter on $date is not fully processed. ($NprocChips $NprocWarps)\n";
    1399                     }
    1400                     $is_processing = 1;
    1401                 }
     1395        if ($science_config{$target}{DIFFABLE} == 1) {
     1396
     1397            my $config_reduction = "DEFAULT";
     1398            if($science_config{$target}{REDUCTION}) {$config_reduction=$science_config{$target}{REDUCTION};}
     1399            print STDERR "execute_diffs: Trying target $target on $date $camera $science_config{$target}{REDUCTION} $config_reduction\n";
     1400
     1401            my $recipe_psastro = $ipprcam->reduction($config_reduction, 'PSASTRO'); # Recipe to use
     1402            &my_die("Unrecognised PSASTRO recipe", $PS_EXIT_CONFIG_ERROR) unless defined $recipe_psastro;
     1403
     1404            my $recipeData;
     1405            {
     1406                # Get the PSASTRO recipe
     1407                my $command = "$ppConfigDump -camera $camera -recipe PSASTRO $recipe_psastro -dump-recipe PSASTRO -";
     1408                my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     1409                    run(command => $command);
     1410                unless ($success) {
     1411                    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     1412                    &my_die("Unable to perform ppConfigDump: $error_code", $PS_EXIT_CONFIG_ERROR);
     1413                }
     1414                $recipeData = $mdcParser->parse(join "", @$stdout_buf) or
     1415                    &my_die("Unable to parse metadata config doc", $PS_EXIT_CONFIG_ERROR);
     1416            }
     1417
     1418            my $maxFWHM = metadataLookupF32($recipeData, 'PSASTRO.MAX.ALLOWED.FWHM');
     1419            print STDERR "execute_diffs: Max FWHM= $maxFWHM for $target\n";
     1420
     1421            foreach my $filter (@filter_list) {
     1422                $Npotential ++;
     1423                my ($NprocChips,$NprocWarps) = pre_diff_queue($date,$observing_state,$target,$filter);
     1424                if ((!defined($force_diff_count))&&($NprocChips != $NprocWarps)) {
     1425                    if ($debug == 1) {
     1426                        print STDERR "execute_diffs: Target $target in filter $filter on $date is not fully processed. ($NprocChips $NprocWarps)\n";
     1427                    }
     1428                    $is_processing = 1;
     1429                }
    14021430                if ($NprocChips == 0) {
    1403                     $Nnoexp ++;
    1404                     if ($debug == 1) {
    1405                         print STDERR "execute_diffs: Target $target in filter $filter on $date has no exposures.\n";
    1406                     }
     1431                    $Nnoexp ++;
     1432                    if ($debug == 1) {
     1433                        print STDERR "execute_diffs: Target $target in filter $filter on $date has no exposures.\n";
     1434                    }
    14071435                    next;
    14081436                }
     
    14101438                    $metadata_out{nsDiffState} = 'QUEUEDIFFS';
    14111439                }
    1412                 if ($debug == 1) {
    1413                     print STDERR "execute_diffs: Target $target in filter $filter on $date has exposures and will be queued.\n";
    1414                 }
    1415                 diff_queue($date,$target,$filter,$pretend);
    1416 
    1417                 #Queue up desperate diffs if the conditions are right for them  
    1418                 if ((defined($science_config{$target}{DESPERATE_DIFFS})) && ($science_config{$target}{DESPERATE_DIFFS} == 1)) {
    1419                     desperate_diff_singles($date,$target,$filter,$pretend);
    1420                 }
    1421 
    1422                 if (defined($pretend)) {
    1423                     add_to_macro_list('check_diffs',$science_config{$target}{DIFFABLE},$date,$target,$filter);
    1424                 }
    1425                 else {
    1426                     add_to_macro_list('queue_diffs',$science_config{$target}{DIFFABLE},$date,$target,$filter);
    1427                 }
    1428             }
    1429         }
    1430         else {
    1431             if ($debug == 1) {
    1432                 print STDERR "execute_diffs: Target $target is not auto-diffable.\n";
    1433             }
     1440                if ($debug == 1) {
     1441                    print STDERR "execute_diffs: Target $target in filter $filter on $date has exposures and will be queued.\n";
     1442                }
     1443                diff_queue($date,$target,$filter,$maxFWHM,$pretend);
     1444
     1445                #Queue up desperate diffs if the conditions are right for them
     1446                if ((defined($science_config{$target}{DESPERATE_DIFFS})) && ($science_config{$target}{DESPERATE_DIFFS} == 1)) {
     1447                    desperate_diff_singles($date,$target,$filter,$maxFWHM,$pretend);
     1448                }
     1449
     1450                if (defined($pretend)) {
     1451                    add_to_macro_list('check_diffs',$science_config{$target}{DIFFABLE},$date,$target,$filter);
     1452                }
     1453                else {
     1454                    add_to_macro_list('queue_diffs',$science_config{$target}{DIFFABLE},$date,$target,$filter);
     1455                }
     1456            }
     1457        }
     1458        else {
     1459            if ($debug == 1) {
     1460                print STDERR "execute_diffs: Target $target is not auto-diffable.\n";
     1461            }
    14341462        }
    14351463    }
    14361464    if ($debug == 1) {
    1437         print "$metadata_out{nsObservingState} $metadata_out{nsDiffPotential} $metadata_out{nsDiffQueued} $is_processing $is_registering\n";
     1465        print "$metadata_out{nsObservingState} $metadata_out{nsDiffPotential} $metadata_out{nsDiffQueued} $is_processing $is_registering\n";
    14381466    }
    14391467
    14401468    if ($metadata_out{nsObservingState} eq 'END_OF_NIGHT') {
    1441         if ($is_processing == 1) {
    1442             $metadata_out{nsDiffState} = 'DIFFING';
    1443         }
    1444         elsif ($is_registering == 0) {
    1445             if ($Npotential == $Nnoexp) {
    1446                 $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
    1447             }
    1448             elsif ($metadata_out{nsDiffPotential} == $metadata_out{nsDiffQueued}) {
    1449                 $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
    1450             }
    1451         }
    1452         else {
    1453             $metadata_out{nsDiffState} = 'DIFFING';
    1454         }
     1469        if ($is_processing == 1) {
     1470            $metadata_out{nsDiffState} = 'DIFFING';
     1471        }
     1472        elsif ($is_registering == 0) {
     1473            if ($Npotential == $Nnoexp) {
     1474                $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
     1475            }
     1476            elsif ($metadata_out{nsDiffPotential} == $metadata_out{nsDiffQueued}) {
     1477                $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
     1478            }
     1479        }
     1480        else {
     1481            $metadata_out{nsDiffState} = 'DIFFING';
     1482        }
    14551483    }
    14561484    else {
    1457         $metadata_out{nsDiffState} = 'DIFFING';
     1485        $metadata_out{nsDiffState} = 'DIFFING';
    14581486    }
    14591487    if ($metadata_out{nsDiffState} eq 'FINISHED_DIFFS') {
    1460         foreach my $target (sort (keys %science_config)) {
    1461             # CZW: We should only arrive at this point once, so we can construct a diff report and mail it now.
    1462             if ((defined($science_config{$target}{DESPERATE_DIFFS})) && ($science_config{$target}{DESPERATE_DIFFS} == 1)) {
    1463                 foreach my $filter (@filter_list) {
    1464                     desperate_diff_queue($date,$target,$filter,$pretend);
    1465                 }
    1466             }
    1467 
    1468             if ((defined($science_config{$target}{SELF_WSDIFFS})) && ($science_config{$target}{SELF_WSDIFFS} == 1)) {
    1469                 foreach my $filter (@filter_list) {
    1470                     # This one needs to return a state to see if we need to wait on stacking before checking again.
    1471                     $metadata_out{nsDiffState} = self_WS_diff_queue($date,$target,$filter,$pretend);
    1472                 }
    1473             }
    1474         }
     1488        foreach my $target (sort (keys %science_config)) {
     1489
     1490            my $config_reduction = "DEFAULT";
     1491            if($science_config{$target}{REDUCTION}) {$config_reduction=$science_config{$target}{REDUCTION};}
     1492            print STDERR "execute_diffs: Trying target $target on $date $camera $science_config{$target}{REDUCTION} $config_reduction\n";
     1493
     1494            my $recipe_psastro = $ipprcam->reduction($config_reduction, 'PSASTRO'); # Recipe to use
     1495            &my_die("Unrecognised PSASTRO recipe", $PS_EXIT_CONFIG_ERROR) unless defined $recipe_psastro;
     1496
     1497            my $recipeData;
     1498            {
     1499                # Get the PSASTRO recipe
     1500                my $command = "$ppConfigDump -camera $camera -recipe PSASTRO $recipe_psastro -dump-recipe PSASTRO -";
     1501                my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     1502                    run(command => $command);
     1503                unless ($success) {
     1504                    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     1505                    &my_die("Unable to perform ppConfigDump: $error_code", $PS_EXIT_CONFIG_ERROR);
     1506                }
     1507                $recipeData = $mdcParser->parse(join "", @$stdout_buf) or
     1508                    &my_die("Unable to parse metadata config doc", $PS_EXIT_CONFIG_ERROR);
     1509            }
     1510
     1511            my $maxFWHM = metadataLookupF32($recipeData, 'PSASTRO.MAX.ALLOWED.FWHM');
     1512
     1513            # CZW: We should only arrive at this point once, so we can construct a diff report and mail it now.
     1514            if ((defined($science_config{$target}{DESPERATE_DIFFS})) && ($science_config{$target}{DESPERATE_DIFFS} == 1)) {
     1515                foreach my $filter (@filter_list) {
     1516                    desperate_diff_queue($date,$target,$filter,$maxFWHM,$pretend);
     1517                }
     1518            }
     1519
     1520            if ((defined($science_config{$target}{SELF_WSDIFFS})) && ($science_config{$target}{SELF_WSDIFFS} == 1)) {
     1521                foreach my $filter (@filter_list) {
     1522                    # This one needs to return a state to see if we need to wait on stacking before checking again.
     1523                    $metadata_out{nsDiffState} = self_WS_diff_queue($date,$target,$filter,$pretend);
     1524                }
     1525            }
     1526        }
    14751527    }
    14761528
    14771529#     if (($Npotential == $Nnoexp)&&($metadata_out{nsObservingState} eq 'END_OF_NIGHT')&&($is_processing == 0)) {
    1478 #       $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
    1479 #     } 
     1530#       $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
     1531#     }
    14801532
    14811533#     if ($is_processing == 1) {
    1482 #       $metadata_out{nsDiffState} = 'DIFFING';
     1534#       $metadata_out{nsDiffState} = 'DIFFING';
    14831535#     }
    14841536}
     
    14881540    my $target = shift;
    14891541    my $filter = shift;
     1542    my $maxFWHM = shift;
    14901543    my $pretend = shift;
    14911544    my ($label,$workdir,$obs_mode,$object,$comment,$tess_id,$dist_group,$data_group,$reduction) = get_tool_parameters($date,$target);
     
    15001553    my $Npotential = 0;
    15011554    my $Nqueued = 0;
    1502     
     1555   
    15031556    foreach my $object_row (@{ $object_ref }) {
    1504         my $this_object = shift @{ $object_row };       
    1505         my $this_chunk = shift @{ $object_row };
    1506         my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state,camProcessedExp.quality FROM ";
    1507         $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN camProcessedExp USING(cam_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
    1508         $input_sth .=   " WHERE chipRun.label = '$label' AND chipRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
    1509         $input_sth .=   " AND substr(rawExp.comment, 1, position(' ' in rawExp.comment)) = '$this_chunk' ORDER BY dateobs ";
    1510 
    1511         my $warps = $db->selectall_arrayref( $input_sth );
    1512 
    1513         # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
    1514         my %comment_hash = ();
    1515         foreach my $this_warp (@{ $warps }) {
    1516             my $this_comment = ${ $this_warp }[3];
    1517             my $this_exp_id  = ${ $this_warp }[0];
    1518             my $this_quality = ${ $this_warp }[5];
    1519             if ($this_quality != 0) {
    1520                 print STDERR "diff_queue: excluding $this_exp_id for $this_object due to non-zero cam.quality $this_quality\n";
    1521             }
    1522             else {
    1523                 $comment_hash{$this_comment} = $this_exp_id;
    1524             }
    1525         }
    1526         # Exclude any warps that are not stored in the comment_hash.
    1527         my @keep_warps = ();
    1528         foreach my $this_warp (@{ $warps }) {
    1529             my $this_comment = ${ $this_warp }[3];
    1530             my $this_exp_id  = ${ $this_warp }[0];
    1531             if ((exists($comment_hash{$this_comment}))&&
    1532                 ($comment_hash{$this_comment} == $this_exp_id)) {
    1533                 push @keep_warps, $this_warp;
    1534             }
    1535             else {
    1536                 print STDERR "diff_queue: excluding $this_exp_id for $this_object due to not being an accepted comment string $this_comment\n";
    1537             }
    1538         }
    1539         @{ $warps } = @keep_warps;
    1540 
    1541         # Exclude the last entry if we do not have an even number of warps.
    1542         if (($#{ $warps } + 1) % 2 != 0) {
    1543             print STDERR "diff_queue: Number of input warps to make diffs is not even for target $target and object $this_object! $#{ $warps } ";
    1544             if ($#{ $warps} + 1 == 1) {
    1545                 print STDERR ": I can do no diffs with only one exposure.\n";
    1546                 next;
    1547             }
    1548             else {
    1549                 my $rejected_warp = pop @{ $warps };
    1550                 my $rejected_exp_id = ${ $rejected_warp }[0];
    1551                 print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
    1552             }
    1553         }
    1554        
    1555         while ($#{ $warps } > -1) {
    1556             # The array is sorted in pairs of input/template.
    1557             my $input_warp = shift @{ $warps };
    1558             my $template_warp = shift @{ $warps };
    1559 
    1560             my $input_exp_id = ${ $input_warp }[0];
    1561             my $input_comment = ${ $input_warp }[3];
    1562 
    1563             my $template_exp_id = ${ $template_warp }[0];
    1564             my $template_comment = ${ $template_warp }[3];
    1565 
    1566             my $input_warp_id = ${ $input_warp }[1];
    1567             my $template_warp_id = ${ $template_warp }[1];
    1568 
    1569             my $input_warp_state = ${ $input_warp }[4];
    1570             my $template_warp_state = ${ $template_warp }[4];
    1571 
    1572             my $input_warp_camQuality = ${ $input_warp }[5];
    1573             my $template_warp_camQuality = ${ $template_warp }[5];
    1574 
    1575             $Npotential++;
    1576 
    1577             unless (defined($input_warp_id) && defined($template_warp_id) &&
    1578                     ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
    1579                 print STDERR "Diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
    1580                 if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
    1581                     # This should now never be reached.
    1582                     # CZW: Trigger backup plan here?  Or simply set up framework?
    1583                     print STDERR "  ...but this is due to a camera stage astrometry quality\n";
    1584                     $Npotential--;
    1585                 }
    1586                 next;
    1587             }
    1588 
    1589             if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
    1590                 $Nqueued++;
    1591                 print STDERR "Diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
    1592                 next;
    1593             }
    1594             else {
    1595                 print STDERR "Preparing to diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
    1596             }
     1557        my $this_object = shift @{ $object_row };       
     1558        my $this_chunk = shift @{ $object_row };
     1559        my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state,camProcessedExp.quality FROM ";
     1560        $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN camProcessedExp USING(cam_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
     1561        $input_sth .=   " WHERE chipRun.label = '$label' AND chipRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
     1562        $input_sth .=   " AND camProcessedExp.fwhm_major <= $maxFWHM ";
     1563        $input_sth .=   " AND substr(rawExp.comment, 1, position(' ' in rawExp.comment)) = '$this_chunk' ORDER BY rawExp.comment,dateobs ";
     1564
     1565        my $warps = $db->selectall_arrayref( $input_sth );
     1566
     1567        # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
     1568        my %comment_hash = ();
     1569        my $Nbad = 0;
     1570        foreach my $this_warp (@{ $warps }) {
     1571            my $this_comment = ${ $this_warp }[3];
     1572            my $this_exp_id  = ${ $this_warp }[0];
     1573            my $this_quality = ${ $this_warp }[5];
     1574            my $this_state   = ${ $this_warp }[4];
     1575            my $this_warp_id  = ${ $this_warp }[1];
    15971576           
    1598             my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
    1599             $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
    1600             $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
    1601             $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
    1602             $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
    1603 #               $cmd .= " -pretend ";
    1604             if (defined($reduction)) {
    1605                 $cmd .= " -set_reduction $reduction ";
    1606             }
    1607 
    1608             if (defined($pretend)) {
    1609                 $cmd .= ' -pretend ';
    1610             }
    1611             if ($debug == 1) {
    1612                 $cmd .= ' -pretend ';
    1613                 print STDERR "diff_queue: $cmd\n";
    1614                 print STDERR " $input_warp_id $template_warp_id\n";
    1615             }
    1616            
    1617             if (($debug == 0)&&(!defined($pretend))) {
    1618                 my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    1619                     run ( command => $cmd, verbose => $verbose );
    1620                 unless ($success) {
    1621                     $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    1622                     &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    1623                 }
    1624                 $Nqueued++;
    1625             }
    1626         }
     1577            #find exposures for this object that have not been fully processed
     1578            if (($this_warp_id eq 'NULL') && (($this_quality == 0) || ($this_quality eq 'NULL')) ) {
     1579                $Nbad += 1;
     1580            }
     1581
     1582            if (($this_quality != 0) || ($this_state eq 'drop') ) {
     1583                print STDERR "diff_queue: excluding $this_exp_id for $this_object due to non-zero cam.quality $this_quality or state $this_state\n";
     1584            }
     1585            else {
     1586                $comment_hash{$this_comment} = $this_exp_id;
     1587            }
     1588        }
     1589
     1590        #kick object out of diff consideration if it has exposures not fully processed
     1591        if ($Nbad > 0) {
     1592            print STDERR "diff_queue: excluding $this_object from making diffs due to not being fully processed to warp stage\n";
     1593            next;
     1594        }
     1595
     1596        # Exclude any warps that are not stored in the comment_hash.
     1597        my @keep_warps = ();
     1598        foreach my $this_warp (@{ $warps }) {
     1599            my $this_comment = ${ $this_warp }[3];
     1600            my $this_exp_id  = ${ $this_warp }[0];
     1601            if ((exists($comment_hash{$this_comment}))&&
     1602                ($comment_hash{$this_comment} == $this_exp_id)) {
     1603                push @keep_warps, $this_warp;
     1604            }
     1605            else {
     1606                print STDERR "diff_queue: excluding $this_exp_id for $this_object due to not being an accepted comment string $this_comment\n";
     1607            }
     1608        }
     1609        @{ $warps } = @keep_warps;
     1610
     1611        # Exclude the last entry if we do not have an even number of warps.
     1612        if (($#{ $warps } + 1) % 2 != 0) {
     1613            print STDERR "diff_queue: Number of input warps to make diffs is not even for target $target and object $this_object! $#{ $warps } ";
     1614            if ($#{ $warps} + 1 == 1) {
     1615                print STDERR ": I can do no diffs with only one exposure.\n";
     1616                next;
     1617            }
     1618            else {
     1619                my $rejected_warp = pop @{ $warps };
     1620                my $rejected_exp_id = ${ $rejected_warp }[0];
     1621                print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
     1622            }
     1623        }
     1624       
     1625        while ($#{ $warps } > -1) {
     1626            # The array is sorted in pairs of input/template.
     1627            my $input_warp = shift @{ $warps };
     1628            my $template_warp = shift @{ $warps };
     1629
     1630            my $input_exp_id = ${ $input_warp }[0];
     1631            my $input_comment = ${ $input_warp }[3];
     1632
     1633            my $template_exp_id = ${ $template_warp }[0];
     1634            my $template_comment = ${ $template_warp }[3];
     1635
     1636            my $input_warp_id = ${ $input_warp }[1];
     1637            my $template_warp_id = ${ $template_warp }[1];
     1638
     1639            my $input_warp_state = ${ $input_warp }[4];
     1640            my $template_warp_state = ${ $template_warp }[4];
     1641
     1642            my $input_warp_camQuality = ${ $input_warp }[5];
     1643            my $template_warp_camQuality = ${ $template_warp }[5];
     1644
     1645            $Npotential++;
     1646
     1647            unless (defined($input_warp_id) && defined($template_warp_id) &&
     1648                    ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
     1649                print STDERR "Diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
     1650                if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
     1651                    # This should now never be reached.
     1652                    # CZW: Trigger backup plan here?  Or simply set up framework?
     1653                    print STDERR "  ...but this is due to a camera stage astrometry quality\n";
     1654                    $Npotential--;
     1655                }
     1656                next;
     1657            }
     1658
     1659            if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
     1660                $Nqueued++;
     1661                print STDERR "Diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     1662                next;
     1663            }
     1664            else {
     1665                print STDERR "Preparing to diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     1666            }
     1667           
     1668            my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
     1669            $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
     1670            $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
     1671            $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
     1672            $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
     1673#               $cmd .= " -pretend ";
     1674            if (defined($reduction)) {
     1675                $cmd .= " -set_reduction $reduction ";
     1676            }
     1677
     1678            if (defined($pretend)) {
     1679                $cmd .= ' -pretend ';
     1680            }
     1681            if ($debug == 1) {
     1682                $cmd .= ' -pretend ';
     1683                print STDERR "diff_queue: $cmd\n";
     1684                print STDERR " $input_warp_id $template_warp_id\n";
     1685            }
     1686           
     1687            if (($debug == 0)&&(!defined($pretend))) {
     1688                my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     1689                    run ( command => $cmd, verbose => $verbose );
     1690                unless ($success) {
     1691                    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     1692                    &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     1693                }
     1694                $Nqueued++;
     1695            }
     1696        }
    16271697    }
    16281698    $metadata_out{nsDiffPotential} += $Npotential;
    16291699    $metadata_out{nsDiffQueued}    += $Nqueued;
    16301700#      if (($metadata_out{nsDiffPotential} == $metadata_out{nsDiffQueued})&&($metadata_out{nsObservingState} eq 'END_OF_NIGHT')) {
    1631      $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
    1632 #      }       
     1701     $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
     1702#      }       
    16331703
    16341704}
     
    16381708    my $target = shift;
    16391709    my $filter = shift;
     1710    my $maxFWHM = shift;
    16401711    my $pretend = shift;
    16411712    my ($label,$workdir,$obs_mode,$object,$comment,$tess_id,$dist_group,$data_group,$reduction) = get_tool_parameters($date,$target);
     
    16541725    my $Nqueued = 0;
    16551726
    1656     #Before considering making diffs, we should check if there are no issues with summit download and/or registration. 
     1727    #Before considering making diffs, we should check if there are no issues with summit download and/or registration.
    16571728    #summitExp has limited information, so see if the number of exps in rawExp and summitExp match up before most recent dateobs of chunk
    16581729    #be careful here, since dateobs is not quite completely the same in both tables. Therefore, allow numbers to be off by 1
     
    16721743        $rawdate=~/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
    16731744        my $date1=DateTime->new(year=>$1,month=>$2,day=>$3,hour=>$4,minute=>$5,second=>$6,time_zone=>"UTC");
    1674   
     1745 
    16751746        $summitdate=~/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
    16761747        my $date2=DateTime->new(year=>$1,month=>$2,day=>$3,hour=>$4,minute=>$5,second=>$6,time_zone=>"UTC");
     
    16851756    if (($summittimediff > 10.)||($noff >10)) {
    16861757        if ($debug == 1) {
    1687         print STDERR "desp_diff_singles: No desperate diffs will be attempted, since the number of exps at the summit and in rawExp do not match ($nsummitexps $nrawexps), or the timestamps are off ($summittimediff)\n";
    1688         }
    1689     }
    1690     else {    
     1758        print STDERR "desp_diff_singles: No desperate diffs will be attempted, since the number of exps at the summit and in rawExp do not match ($nsummitexps $nrawexps), or the timestamps are off ($summittimediff)\n";
     1759        }
     1760    }
     1761    else {   
    16911762        foreach my $object_row (@{ $object_ref }) {
    1692             my $this_object = shift @{ $object_row };
    1693             my $this_chunk = shift @{ $object_row };
    1694        
    1695             my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state,camProcessedExp.quality,substr(comment, 1, position(' ' in comment)) FROM ";
    1696             $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN camProcessedExp USING(cam_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
    1697             $input_sth .=   " WHERE chipRun.label = '$label' AND chipRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
    1698             $input_sth .=   " AND substr(rawExp.comment, 1, position(' ' in rawExp.comment)) = '$this_chunk' ORDER BY dateobs ";
    1699 
    1700             my $warps = $db->selectall_arrayref( $input_sth );
    1701 
    1702             # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
    1703             my %comment_hash = ();
    1704             foreach my $this_warp (@{ $warps }) {
    1705                 my $this_comment = ${ $this_warp }[3];
    1706                 my $this_exp_id  = ${ $this_warp }[0];
    1707                 my $this_quality = ${ $this_warp }[5];
    1708                 if ($this_quality != 0) {
    1709                     print STDERR "desp_diff_singles: excluding $this_exp_id for $this_object due to non-zero cam.quality $this_quality\n";
    1710                 }
    1711                 else {
    1712                     $comment_hash{$this_comment} = $this_exp_id;
    1713                 }
    1714             }
    1715             # Exclude any warps that are not stored in the comment_hash.
    1716             my @keep_warps = ();
    1717             foreach my $this_warp (@{ $warps }) {
    1718                 my $this_comment = ${ $this_warp }[3];
    1719                 my $this_exp_id  = ${ $this_warp }[0];
    1720                 if ((exists($comment_hash{$this_comment}))&&
    1721                     ($comment_hash{$this_comment} == $this_exp_id)) {
    1722                     push @keep_warps, $this_warp;
     1763            my $this_object = shift @{ $object_row };
     1764            my $this_chunk = shift @{ $object_row };
     1765       
     1766            my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state,camProcessedExp.quality,substr(comment, 1, position(' ' in comment)),camProcessedExp.fwhm_major FROM ";
     1767            $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN camProcessedExp USING(cam_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
     1768            $input_sth .=   " WHERE chipRun.label = '$label' AND chipRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
     1769            $input_sth .=   " AND substr(rawExp.comment, 1, position(' ' in rawExp.comment)) = '$this_chunk' ORDER BY rawExp.comment,dateobs ";
     1770
     1771            my $warps = $db->selectall_arrayref( $input_sth );
     1772            my $warpsBQ = $db->selectall_arrayref( $input_sth );;
     1773
     1774            # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
     1775            my %comment_hash = ();
     1776            my %comment_hash_good = ();
     1777            my $Nbad = 0;
     1778            foreach my $this_warp (@{ $warps }) {
     1779                my $this_comment = ${ $this_warp }[3];
     1780                my $this_exp_id  = ${ $this_warp }[0];
     1781                my $this_quality = ${ $this_warp }[5];
     1782                my $this_state   = ${ $this_warp }[4];
     1783                my $this_fwhm   = ${ $this_warp }[7];
     1784                my $this_warp_id  = ${ $this_warp }[1];
     1785
     1786                #find exposures for this object that have not been fully processed
     1787                if (($this_warp_id eq 'NULL') && (($this_quality == 0) || ($this_quality eq 'NULL')) ) {
     1788                    $Nbad += 1;
     1789                }
     1790
     1791                if (($this_quality != 0) || ($this_state eq 'drop') || ($this_fwhm > $maxFWHM)) {
     1792                    print STDERR "desp_diff_singles: excluding $this_exp_id for $this_object due to non-zero cam.quality $this_quality or state $this_state or FWHM $this_fwhm\n";
     1793                }
     1794                else {
     1795                    $comment_hash_good{$this_comment} = $this_exp_id;
     1796                }
     1797               
     1798                #also save the entries which are ok, but not best quality
     1799                if (($this_quality == 0) && ($this_state ne 'drop') ) {
     1800                    $comment_hash{$this_comment} = $this_exp_id;
     1801                }
     1802            }
     1803
     1804            #kick object out of diff consideration if it has exposures not fully processed
     1805            if ($Nbad > 0) {
     1806                print STDERR "desp_diff_singles: excluding $this_object from making diffs due to not being fully processed to warp stage\n";
     1807                next;
     1808            }
     1809
     1810            # Exclude any warps that are not stored in the comment_hash_good.
     1811            my @keep_warps = ();
     1812            foreach my $this_warp (@{ $warps }) {
     1813                my $this_comment = ${ $this_warp }[3];
     1814                my $this_exp_id  = ${ $this_warp }[0];
     1815                if ((exists($comment_hash_good{$this_comment}))&&
     1816                    ($comment_hash_good{$this_comment} == $this_exp_id)) {
     1817                    push @keep_warps, $this_warp;
    17231818                    $this_date  = ${ $this_warp }[2];
    17241819                    $chunk_name  = ${ $this_warp }[6];
    1725                 }
    1726                 else {
    1727                     print STDERR "desp_diff_singles: excluding $this_exp_id for $this_object due to being rejected $this_comment\n";
    1728                 }
    1729             }
    1730             @{ $warps } = @keep_warps;
    1731 
     1820                }
     1821                else {
     1822                    print STDERR "desp_diff_singles: excluding $this_exp_id for $this_object due to being rejected $this_comment\n";
     1823                }
     1824            }
     1825            @{ $warps } = @keep_warps;
     1826            my $nwarps = ($#{ $warps } + 1);
     1827           
    17321828            #find the time of the most recent exposure in that chunk
    1733             my $input_chunk = "select max(dateobs) FROM rawExp WHERE substr(comment, 1, position(' ' in comment)) = '$chunk_name' AND filter = '$filter' ";
    1734             my $chunk = $db->selectall_arrayref( $input_chunk );
    1735             foreach my $this_chunk (@{ $chunk }) {
    1736                 $this_date = ${ $this_chunk }[0];
     1829            my $input_chunk = "select max(dateobs) FROM rawExp WHERE substr(comment, 1, position(' ' in comment)) = '$chunk_name' AND filter = '$filter' ";
     1830            my $chunk = $db->selectall_arrayref( $input_chunk );
     1831            foreach my $this_chunk (@{ $chunk }) {
     1832                $this_date = ${ $this_chunk }[0];
    17371833            }
    17381834 
    17391835            #compute and store some stats for potential on-the-fly desperate diffs
    1740             my $nwarps = ($#{ $warps } + 1);
    17411836            my $timediff = 0;
    17421837            my $now=DateTime->now;
     
    17501845                }
    17511846            }
    1752 
    1753             #Consider the special case of on-the-fly desperate diffs
    1754             #The conditions are: uneven nr of warps greater than 3, and the most recent observations is more than $desdiffdt hours old
    1755             if (($nwarps % 2 != 0) && ($nwarps >= 3) && ($timediff < $desdiffdt)) {
    1756                 print STDERR "desp_diff_singles: There are potential desperate diffs to be done, but the time criterium is not met.\n";
    1757                 next;
    1758             }
    1759             if (($nwarps % 2 == 0) || ($nwarps == 1) || ($timediff < $desdiffdt)) {
    1760                 next;
    1761             }
    1762 
    1763             # We are attempting to do the missing diffs, so reverse the list of retained warps.
    1764             # Good objects with all visits will be skipped due to the duplicate check.
    1765             # Bad objects will have the earliest visit rejected, and the visits repaired in a way that will produce all desired pairs.
    1766             @{ $warps } = reverse @keep_warps;
    1767 
    1768             # Exclude the last entry if we do not have an even number of warps.
    1769             if (($#{ $warps } + 1) % 2 != 0) {
    1770                 print STDERR "desp_diff_singles: Number of input warps to make diffs is not even for target $target and object $this_object!";
    1771                 my $rejected_warp = pop @{ $warps };
    1772                 my $rejected_exp_id = ${ $rejected_warp }[0];
    1773                 print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
    1774             }
    1775        
    1776             while ($#{ $warps } > -1) {
    1777                 # The array is sorted in pairs of input/template.
    1778                 my $template_warp = shift @{ $warps };
    1779                 my $input_warp = shift @{ $warps };
    1780    
    1781                 my $input_exp_id = ${ $input_warp }[0];
    1782                 my $input_comment = ${ $input_warp }[3];
    1783 
    1784                 my $template_exp_id = ${ $template_warp }[0];
    1785                 my $template_comment = ${ $template_warp }[3];
    1786 
    1787                 my $input_warp_id = ${ $input_warp }[1];
    1788                 my $template_warp_id = ${ $template_warp }[1];
    1789 
    1790                 my $input_warp_state = ${ $input_warp }[4];
    1791                 my $template_warp_state = ${ $template_warp }[4];
    1792 
    1793                 my $input_warp_camQuality = ${ $input_warp }[5];
    1794                 my $template_warp_camQuality = ${ $template_warp }[5];
    1795 
    1796                 $Npotential++;
    1797 
    1798                 unless (defined($input_warp_id) && defined($template_warp_id) &&
    1799                     ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
    1800                     print STDERR "Desp diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
    1801                     if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
    1802                         # This should now never be reached.
    1803                         # CZW: Trigger backup plan here?  Or simply set up framework?
    1804                         print STDERR "  ...but this is due to a camera stage astrometry quality\n";
    1805                         $Npotential--;
    1806                     }
    1807                     next;
    1808                 }
    1809 
    1810                 if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
    1811                     $Nqueued++;
    1812                     print STDERR "Desp diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
    1813                     next;
    1814                 }
    1815                 else {
    1816                     print STDERR "Preparing to diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
    1817                 }
    1818            
    1819                 my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
    1820                 $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
    1821                 $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
    1822                 $cmd .= "-rerun "; # Needed because we may have some diffs that already use some of the exposures
    1823                 $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
    1824                 $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
    1825                 if (defined($reduction)) {
    1826                     $cmd .= " -set_reduction $reduction ";
    1827                 }
    1828        
    1829                 if (defined($pretend)) {
    1830                     $cmd .= ' -pretend ';
    1831                 }
    1832                 if ($debug == 1) {
    1833                     $cmd .= ' -pretend ';
    1834                     print STDERR "desp_diff_singles: $cmd\n";
    1835                     print STDERR " $input_warp_id $template_warp_id\n";
    1836                 }
    1837            
    1838                 if (($debug == 0)&&(!defined($pretend))) {
    1839                     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    1840                         run ( command => $cmd, verbose => $verbose );
    1841                     unless ($success) {
    1842                         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    1843                         &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    1844                     }
    1845                     $Nqueued++;
    1846                 }
    1847             }
     1847           
     1848            ################################
     1849            #We reach a junction here, where having more than 3 (but uneven) warps will result in desperate diffs
     1850            #Conversely, less than 3 good quality warps might result in dirty diffs
     1851            ################################
     1852            if($nwarps >= 3) {     
     1853                #Consider the special case of on-the-fly desperate diffs
     1854                #The conditions are: uneven nr of warps greater than 3, and the most recent observations is more than $desdiffdt hours old
     1855                if (($nwarps % 2 != 0) && ($nwarps >= 3) && ($timediff < $desdiffdt)) {
     1856                    print STDERR "desp_diff_singles: There are potential desperate diffs to be done, but the time criterium is not met.\n";
     1857                    next;
     1858                }
     1859                if (($nwarps % 2 == 0) || ($nwarps == 1) || ($timediff < $desdiffdt)) {
     1860                    next;
     1861                }
     1862
     1863                # We are attempting to do the missing diffs, so reverse the list of retained warps.
     1864                # Good objects with all visits will be skipped due to the duplicate check.
     1865                # Bad objects will have the earliest visit rejected, and the visits repaired in a way that will produce all desired pairs.
     1866                @{ $warps } = reverse @keep_warps;
     1867
     1868                # Exclude the last entry if we do not have an even number of warps.
     1869                if (($#{ $warps } + 1) % 2 != 0) {
     1870                    print STDERR "desp_diff_singles: Number of input warps to make diffs is not even for target $target and object $this_object!";
     1871                    my $rejected_warp = pop @{ $warps };
     1872                    my $rejected_exp_id = ${ $rejected_warp }[0];
     1873                    print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
     1874                }
     1875       
     1876                while ($#{ $warps } > -1) {
     1877                    # The array is sorted in pairs of input/template.
     1878                    my $template_warp = shift @{ $warps };
     1879                    my $input_warp = shift @{ $warps };
     1880   
     1881                    my $input_exp_id = ${ $input_warp }[0];
     1882                    my $input_comment = ${ $input_warp }[3];
     1883
     1884                    my $template_exp_id = ${ $template_warp }[0];
     1885                    my $template_comment = ${ $template_warp }[3];
     1886
     1887                    my $input_warp_id = ${ $input_warp }[1];
     1888                    my $template_warp_id = ${ $template_warp }[1];
     1889
     1890                    my $input_warp_state = ${ $input_warp }[4];
     1891                    my $template_warp_state = ${ $template_warp }[4];
     1892
     1893                    my $input_warp_camQuality = ${ $input_warp }[5];
     1894                    my $template_warp_camQuality = ${ $template_warp }[5];
     1895
     1896                    $Npotential++;
     1897
     1898                    unless (defined($input_warp_id) && defined($template_warp_id) &&
     1899                        ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
     1900                        print STDERR "Desp diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
     1901                        if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
     1902                            # This should now never be reached.
     1903                            # CZW: Trigger backup plan here?  Or simply set up framework?
     1904                            print STDERR "  ...but this is due to a camera stage astrometry quality\n";
     1905                            $Npotential--;
     1906                        }
     1907                        next;
     1908                    }
     1909
     1910                    if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
     1911                        $Nqueued++;
     1912                        print STDERR "Desp diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     1913                        next;
     1914                    }
     1915                    else {
     1916                        print STDERR "Preparing to diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     1917                    }
     1918           
     1919                    my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
     1920                    $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
     1921                    $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
     1922                    $cmd .= "-rerun "; # Needed because we may have some diffs that already use some of the exposures
     1923                    $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
     1924                    $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
     1925                    if (defined($reduction)) {
     1926                        $cmd .= " -set_reduction $reduction ";
     1927                    }
     1928       
     1929                    if (defined($pretend)) {
     1930                        $cmd .= ' -pretend ';
     1931                    }
     1932                    if ($debug == 1) {
     1933                        $cmd .= ' -pretend ';
     1934                        print STDERR "desp_diff_singles: $cmd\n";
     1935                        print STDERR " $input_warp_id $template_warp_id\n";
     1936                    }
     1937           
     1938                    if (($debug == 0)&&(!defined($pretend))) {
     1939                        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     1940                            run ( command => $cmd, verbose => $verbose );
     1941                        unless ($success) {
     1942                            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     1943                            &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     1944                        }
     1945                        $Nqueued++;
     1946                    }
     1947                }           
     1948           
     1949            } else {       
     1950                print STDERR "desp_diff_singles: There is a possibility for dirty diffs to be made\n";     
     1951                #Consider the case of on-the-fly dirty desperate diffs
     1952                #The conditions are: uneven nr of bad quality warps greater than 3, and the most recent observations is more than $desdiffdt hours old
     1953
     1954#                # Exclude any warps that are not stored in the more general comment_hash.
     1955#                my @keep_warps = ();
     1956#                foreach my $this_warp (@{ $warpsBQ }) {
     1957#                    my $this_comment = ${ $this_warp }[3];
     1958#                    my $this_exp_id  = ${ $this_warp }[0];
     1959#                    if ((exists($comment_hash{$this_comment}))&&
     1960#                        ($comment_hash{$this_comment} == $this_exp_id)) {
     1961#                        push @keep_warps, $this_warp;
     1962#                        $this_date  = ${ $this_warp }[2];
     1963#                        $chunk_name  = ${ $this_warp }[6];
     1964#                    }
     1965#                    else {
     1966#                        print STDERR "desp_diff_singles: excluding $this_exp_id for $this_object due to being rejected $this_comment\n";
     1967#                    }
     1968#                }
     1969#                @{ $warpsBQ } = @keep_warps;
     1970#
     1971#                if ($nwarps >= 2) {
     1972#                    #one regular diff has already been made. So, need only one more. Strip a good entry from the array             
     1973#                    my $nrem = 0;
     1974#                    my @keep_warps = ();
     1975#                    foreach my $this_warp (@{ $warpsBQ }) {
     1976#                        my $this_comment = ${ $this_warp }[3];
     1977#                        my $this_exp_id  = ${ $this_warp }[0];
     1978#                        my $this_fwhm   = ${ $this_warp }[7];
     1979#                        if (($nrem <1) && ($this_fwhm <= $maxFWHM)) {
     1980#                            $nrem++;
     1981#                            print STDERR "desp_diff_singles: excluding $this_exp_id for $this_object from dirty desp diffs $this_comment\n";
     1982#                        } else {
     1983#                            push @keep_warps, $this_warp;                       
     1984#                        }
     1985#                    }
     1986#                    @{ $warpsBQ } = @keep_warps;
     1987#                }
     1988#
     1989#                # We are attempting to do the missing diffs, so reverse the list of retained warps.
     1990#                # Good objects with all visits will be skipped due to the duplicate check.
     1991#                # Bad objects will have the earliest visit rejected, and the visits repaired in a way that will produce all desired pairs.
     1992#                @{ $warpsBQ } = reverse @{ $warpsBQ };
     1993#
     1994#                # Exclude the last entry if we do not have an even number of warps.
     1995#                if (($#{ $warpsBQ } + 1) % 2 != 0) {
     1996#                    print STDERR "desp_diff_singles: Number of input warps to make dirty diffs is not even for target $target and object $this_object!";
     1997#                    my $rejected_warp = pop @{ $warpsBQ };
     1998#                    my $rejected_exp_id = ${ $rejected_warp }[0];
     1999#                    print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
     2000#                }
     2001#                my $nwarpsBQ = ($#{$warpsBQ} + 1);
     2002#       
     2003#       
     2004#                if (($nwarpsBQ >= 2) && ($timediff < $desdiffdt)) {
     2005#                    print STDERR "desp_diff_singles: There are potential dirty desperate diffs to be done, but the time criterium is not met.\n";
     2006#                    next;
     2007#                }
     2008#                if (($nwarpsBQ <= 1) || ($timediff < $desdiffdt)) {
     2009#                    next;
     2010#                }
     2011#       
     2012#                while ($#{ $warpsBQ } > -1) {
     2013#                    # The array is sorted in pairs of input/template.
     2014#                    my $template_warp = shift @{ $warpsBQ };
     2015#                    my $input_warp = shift @{ $warpsBQ };
     2016#   
     2017#                    my $input_exp_id = ${ $input_warp }[0];
     2018#                    my $input_comment = ${ $input_warp }[3];
     2019#
     2020#                    my $template_exp_id = ${ $template_warp }[0];
     2021#                    my $template_comment = ${ $template_warp }[3];
     2022#
     2023#                    my $input_warp_id = ${ $input_warp }[1];
     2024#                    my $template_warp_id = ${ $template_warp }[1];
     2025#
     2026#                    my $input_warp_state = ${ $input_warp }[4];
     2027#                    my $template_warp_state = ${ $template_warp }[4];
     2028#
     2029#                    my $input_warp_camQuality = ${ $input_warp }[5];
     2030#                    my $template_warp_camQuality = ${ $template_warp }[5];
     2031#
     2032#                    $Npotential++;
     2033#
     2034#                    unless (defined($input_warp_id) && defined($template_warp_id) &&
     2035#                        ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
     2036#                        print STDERR "Desp diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
     2037#                        if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
     2038#                            # This should now never be reached.
     2039#                            # CZW: Trigger backup plan here?  Or simply set up framework?
     2040#                            print STDERR "  ...but this is due to a camera stage astrometry quality\n";
     2041#                            $Npotential--;
     2042#                        }
     2043#                        next;
     2044#                    }
     2045#
     2046#                    if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
     2047#                        $Nqueued++;
     2048#                        print STDERR "Desp diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     2049#                        next;
     2050#                    }
     2051#                    else {
     2052#                        print STDERR "Preparing to dirty diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     2053#                    }
     2054#           
     2055#                    my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
     2056#                    $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
     2057#                    $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
     2058#                    $cmd .= "-rerun "; # Needed because we may have some diffs that already use some of the exposures
     2059#                    $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
     2060#                    $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
     2061#                    if (defined($reduction)) {
     2062#                        $cmd .= " -set_reduction $reduction ";
     2063#                    }
     2064#       
     2065#                    if (defined($pretend)) {
     2066#                        $cmd .= ' -pretend ';
     2067#                    }
     2068#                    if ($debug == 1) {
     2069#                        $cmd .= ' -pretend ';
     2070#                        print STDERR "desp_diff_singles: $cmd\n";
     2071#                        print STDERR " $input_warp_id $template_warp_id\n";
     2072#                    }
     2073#           
     2074#                    if (($debug == 0)&&(!defined($pretend))) {
     2075#                        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2076#                            run ( command => $cmd, verbose => $verbose );
     2077#                        unless ($success) {
     2078#                            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2079#                            &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2080#                        }
     2081#                        $Nqueued++;
     2082#                    }
     2083#                }
     2084           
     2085           
     2086           
     2087            }
    18482088        }
    18492089    }
     
    18562096    my $target = shift;
    18572097    my $filter = shift;
     2098    my $maxFWHM = shift;
    18582099    my $pretend = shift;
    18592100    my ($label,$workdir,$obs_mode,$object,$comment,$tess_id,$dist_group,$data_group,$reduction) = get_tool_parameters($date,$target);
     
    18702111    my $Nqueued = 0;
    18712112
    1872     #Before considering making diffs, we should check if there are no issues with summit download and/or registration. 
     2113    #Before considering making diffs, we should check if there are no issues with summit download and/or registration.
    18732114    #summitExp has limited information, so see if the number of exps in rawExp and summitExp match up before most recent dateobs of chunk
    18742115    #be careful here, since dateobs is not quite completely the same in both tables. Therefore, allow numbers to be off by 1
     
    18882129        $rawdate=~/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
    18892130        my $date1=DateTime->new(year=>$1,month=>$2,day=>$3,hour=>$4,minute=>$5,second=>$6,time_zone=>"UTC");
    1890   
     2131 
    18912132        $summitdate=~/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
    18922133        my $date2=DateTime->new(year=>$1,month=>$2,day=>$3,hour=>$4,minute=>$5,second=>$6,time_zone=>"UTC");
     
    19012142    if (($summittimediff > 10.)||($noff >10)) {
    19022143        if ($debug == 1) {
    1903         print STDERR "desp_diff_queue: No desperate diffs will be attempted, since the number of exps at the summit and in rawExp do not match ($nsummitexps $nrawexps), or the timestamps are off ($summittimediff)\n";
     2144        print STDERR "desp_diff_queue: No desperate diffs will be attempted, since the number of exps at the summit and in rawExp do not match ($nsummitexps $nrawexps), or the timestamps are off ($summittimediff)\n";
    19042145        }
    19052146    }
    19062147    else {
    19072148        foreach my $object_row (@{ $object_ref }) {
    1908             my $this_object = shift @{ $object_row };
    1909             my $this_chunk = shift @{ $object_row };
    1910        
    1911             my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state,camProcessedExp.quality FROM ";
    1912             $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN camProcessedExp USING(cam_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
    1913             $input_sth .=   " WHERE chipRun.label = '$label' AND chipRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
    1914             $input_sth .=   " AND substr(rawExp.comment, 1, position(' ' in rawExp.comment)) = '$this_chunk' ORDER BY dateobs ";
    1915 
    1916             my $warps = $db->selectall_arrayref( $input_sth );
    1917 
    1918             # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
    1919             my %comment_hash = ();
    1920             foreach my $this_warp (@{ $warps }) {
    1921                 my $this_comment = ${ $this_warp }[3];
    1922                 my $this_exp_id  = ${ $this_warp }[0];
    1923                 my $this_quality = ${ $this_warp }[5];
    1924                 if ($this_quality != 0) {
    1925                     print STDERR "desp_diff_queue: excluding $this_exp_id for $this_object due to non-zero cam.quality $this_quality\n";
    1926                 }
    1927                 else {
    1928                     $comment_hash{$this_comment} = $this_exp_id;
    1929                 }
    1930             }
    1931             # Exclude any warps that are not stored in the comment_hash.
    1932             my @keep_warps = ();
    1933             foreach my $this_warp (@{ $warps }) {
    1934                 my $this_comment = ${ $this_warp }[3];
    1935                 my $this_exp_id  = ${ $this_warp }[0];
    1936                 if ((exists($comment_hash{$this_comment}))&&
    1937                     ($comment_hash{$this_comment} == $this_exp_id)) {
    1938                     push @keep_warps, $this_warp;
    1939                 }
    1940                 else {
    1941                     print STDERR "desp_diff_queue: excluding $this_exp_id for $this_object due to not being an accepted comment string $this_comment\n";
    1942                 }
    1943             }
    1944             # We are attempting to do the missing diffs, so reverse the list of retained warps.
    1945             # Good objects with all visits will be skipped due to the duplicate check.
    1946             # Bad objects will have the earliest visit rejected, and the visits repaired in a way that will produce all desired pairs.
    1947             @{ $warps } = reverse @keep_warps;
    1948                    
    1949             # Exclude the last entry if we do not have an even number of warps.
    1950             if (($#{ $warps } + 1) % 2 != 0) {
    1951                 print STDERR "desp_diff_queue: Number of input warps to make diffs is not even for target $target and object $this_object! $#{ $warps } ";
    1952                 if ($#{ $warps} + 1 == 1) {
    1953                     print STDERR ": I can do no diffs with only one exposure.\n";
    1954                     next;
    1955                 }
    1956                 else {
    1957                     my $rejected_warp = pop @{ $warps };
    1958                     my $rejected_exp_id = ${ $rejected_warp }[0];
    1959                     print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
    1960                 }
    1961             }
    1962        
    1963             while ($#{ $warps } > -1) {
    1964                 # In this mode, the array is sorted in pairs of template/input, counter to the standard queue.
    1965                 my $template_warp = shift @{ $warps };
    1966                 my $input_warp = shift @{ $warps };
    1967 
    1968                 my $input_exp_id = ${ $input_warp }[0];
    1969                 my $input_comment = ${ $input_warp }[3];
    1970 
    1971                 my $template_exp_id = ${ $template_warp }[0];
    1972                 my $template_comment = ${ $template_warp }[3];
    1973 
    1974                 my $input_warp_id = ${ $input_warp }[1];
    1975                 my $template_warp_id = ${ $template_warp }[1];
    1976 
    1977                 my $input_warp_state = ${ $input_warp }[4];
    1978                 my $template_warp_state = ${ $template_warp }[4];
    1979 
    1980                 my $input_warp_camQuality = ${ $input_warp }[5];
    1981                 my $template_warp_camQuality = ${ $template_warp }[5];
    1982 
    1983                 $Npotential++;
    1984 
    1985                 unless (defined($input_warp_id) && defined($template_warp_id) &&
    1986                         ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
    1987                     print STDERR "Diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
    1988                     if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
    1989                         # This should now never be reached.
    1990                         # CZW: Trigger backup plan here?  Or simply set up framework?
    1991                         print STDERR "  ...but this is due to a camera stage astrometry quality\n";
    1992                         $Npotential--;
    1993                     }
    1994                     next;
    1995                 }
    1996 
    1997                 if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
    1998                     $Nqueued++;
    1999                     print STDERR "Diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
    2000                     next;
    2001                 }
    2002                 else {
    2003                     print STDERR "Preparing to diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
    2004                 }
     2149            my $this_object = shift @{ $object_row };
     2150            my $this_chunk = shift @{ $object_row };
     2151       
     2152            my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state,camProcessedExp.quality,camProcessedExp.fwhm_major FROM ";
     2153            $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN camProcessedExp USING(cam_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
     2154            $input_sth .=   " WHERE chipRun.label = '$label' AND chipRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
     2155            $input_sth .=   " AND substr(rawExp.comment, 1, position(' ' in rawExp.comment)) = '$this_chunk' ORDER BY rawExp.comment,dateobs ";
     2156
     2157            my $warps = $db->selectall_arrayref( $input_sth );
     2158            my $warpsBQ = $db->selectall_arrayref( $input_sth );;
     2159
     2160            # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
     2161            my %comment_hash = ();
     2162            my %comment_hash_good = ();
     2163            my $Nbad = 0;
     2164            foreach my $this_warp (@{ $warps }) {
     2165                my $this_comment = ${ $this_warp }[3];
     2166                my $this_exp_id  = ${ $this_warp }[0];
     2167                my $this_quality = ${ $this_warp }[5];
     2168                my $this_state   = ${ $this_warp }[4];
     2169                my $this_fwhm    = ${ $this_warp }[7];
     2170                my $this_warp_id  = ${ $this_warp }[1];
     2171
     2172                #find exposures for this object that have not been fully processed
     2173                if (($this_warp_id eq 'NULL') && (($this_quality == 0) || ($this_quality eq 'NULL')) ) {
     2174                    $Nbad += 1;
     2175                }
     2176
     2177                if (($this_quality != 0) || ($this_state eq 'drop') || ($this_fwhm > $maxFWHM)) {
     2178                    print STDERR "desp_diff_queue: excluding $this_exp_id for $this_object due to non-zero cam.quality $this_quality or state $this_state or FWHM $this_fwhm\n";
     2179                }
     2180                else {
     2181                    $comment_hash_good{$this_comment} = $this_exp_id;
     2182                }
     2183               
     2184                #also save the entries which are ok, but not best quality
     2185                if (($this_quality == 0) && ($this_state ne 'drop') ) {
     2186                    $comment_hash{$this_comment} = $this_exp_id;
     2187                }
     2188            }
     2189
     2190            #kick object out of diff consideration if it has exposures not fully processed
     2191            if ($Nbad > 0) {
     2192                print STDERR "desp_diff_queue: excluding $this_object from making diffs due to not being fully processed to warp stage\n";
     2193                next;
     2194            }
     2195
     2196            # Exclude any warps that are not stored in the comment_hash_good.
     2197            my @keep_warps = ();
     2198            foreach my $this_warp (@{ $warps }) {
     2199                my $this_comment = ${ $this_warp }[3];
     2200                my $this_exp_id  = ${ $this_warp }[0];
     2201                if ((exists($comment_hash_good{$this_comment}))&&
     2202                    ($comment_hash_good{$this_comment} == $this_exp_id)) {
     2203                    push @keep_warps, $this_warp;
     2204                    my $this_date  = ${ $this_warp }[2];
     2205                    my $chunk_name  = ${ $this_warp }[6];
     2206                }
     2207                else {
     2208                    print STDERR "desp_diff_queue: excluding $this_exp_id for $this_object due to being rejected $this_comment\n";
     2209                }
     2210            }
     2211            @{ $warps } = @keep_warps;
     2212            my $nwarps = ($#{ $warps } + 1);
     2213
     2214            ################################
     2215            #We reach a junction here, where having more than 3 (but uneven) warps will result in desperate diffs
     2216            #Conversely, less than 3 warps might result in dirty diffs
     2217            ################################
     2218            if($nwarps >= 3) {     
     2219                # We are attempting to do the missing diffs, so reverse the list of retained warps.
     2220                # Good objects with all visits will be skipped due to the duplicate check.
     2221                # Bad objects will have the earliest visit rejected, and the visits repaired in a way that will produce all desired pairs.
     2222                @{ $warps } = reverse @keep_warps;
     2223
     2224                # Exclude the last entry if we do not have an even number of warps.
     2225                if (($#{ $warps } + 1) % 2 != 0) {
     2226                    print STDERR "desp_diff_queue: Number of input warps to make diffs is not even for target $target and object $this_object! $#{ $warps } ";
     2227                    if ($#{ $warps} + 1 == 1) {
     2228                        print STDERR ": I can do no diffs with only one exposure.\n";
     2229                        next;
     2230                    }
     2231                    else {
     2232                        my $rejected_warp = pop @{ $warps };
     2233                        my $rejected_exp_id = ${ $rejected_warp }[0];
     2234                        print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
     2235                    }
     2236                }
     2237       
     2238                while ($#{ $warps } > -1) {
     2239                    # The array is sorted in pairs of input/template.
     2240                    my $template_warp = shift @{ $warps };
     2241                    my $input_warp = shift @{ $warps };
     2242   
     2243                    my $input_exp_id = ${ $input_warp }[0];
     2244                    my $input_comment = ${ $input_warp }[3];
     2245
     2246                    my $template_exp_id = ${ $template_warp }[0];
     2247                    my $template_comment = ${ $template_warp }[3];
     2248
     2249                    my $input_warp_id = ${ $input_warp }[1];
     2250                    my $template_warp_id = ${ $template_warp }[1];
     2251
     2252                    my $input_warp_state = ${ $input_warp }[4];
     2253                    my $template_warp_state = ${ $template_warp }[4];
     2254
     2255                    my $input_warp_camQuality = ${ $input_warp }[5];
     2256                    my $template_warp_camQuality = ${ $template_warp }[5];
     2257
     2258                    $Npotential++;
     2259
     2260                    unless (defined($input_warp_id) && defined($template_warp_id) &&
     2261                        ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
     2262                        print STDERR "Desp diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
     2263                        if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
     2264                            # This should now never be reached.
     2265                            # CZW: Trigger backup plan here?  Or simply set up framework?
     2266                            print STDERR "  ...but this is due to a camera stage astrometry quality\n";
     2267                            $Npotential--;
     2268                        }
     2269                        next;
     2270                    }
     2271
     2272                    if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
     2273                        $Nqueued++;
     2274                        print STDERR "Desp diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     2275                        next;
     2276                    }
     2277                    else {
     2278                        print STDERR "Preparing to diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     2279                    }
     2280           
     2281                    my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
     2282                    $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
     2283                    $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
     2284                    $cmd .= "-rerun "; # Needed because we may have some diffs that already use some of the exposures
     2285                    $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
     2286                    $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
     2287                    if (defined($reduction)) {
     2288                        $cmd .= " -set_reduction $reduction ";
     2289                    }
     2290       
     2291                    if (defined($pretend)) {
     2292                        $cmd .= ' -pretend ';
     2293                    }
     2294                    if ($debug == 1) {
     2295                        $cmd .= ' -pretend ';
     2296                        print STDERR "desp_diff_queue: $cmd\n";
     2297                        print STDERR " $input_warp_id $template_warp_id\n";
     2298                    }
     2299           
     2300                    if (($debug == 0)&&(!defined($pretend))) {
     2301                        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2302                            run ( command => $cmd, verbose => $verbose );
     2303                        unless ($success) {
     2304                            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2305                            &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2306                        }
     2307                        $Nqueued++;
     2308                    }
     2309                }           
     2310           
     2311            } else {       
     2312                print STDERR "desp_diff_queue: There is a possibility for dirty diffs to be made\n";
     2313                #Consider the case of on-the-fly dirty desperate diffs
     2314                #The conditions are: uneven nr of bad quality warps greater than 3, and the most recent observations is more than $desdiffdt hours old
     2315
     2316#                # Exclude any warps that are not stored in the more general comment_hash.
     2317#                my @keep_warps = ();
     2318#                foreach my $this_warp (@{ $warpsBQ }) {
     2319#                    my $this_comment = ${ $this_warp }[3];
     2320#                    my $this_exp_id  = ${ $this_warp }[0];
     2321#                    if ((exists($comment_hash{$this_comment}))&&
     2322#                        ($comment_hash{$this_comment} == $this_exp_id)) {
     2323#                        push @keep_warps, $this_warp;
     2324#                        my $this_date  = ${ $this_warp }[2];
     2325#                        my $chunk_name  = ${ $this_warp }[6];
     2326#                    }
     2327#                    else {
     2328#                        print STDERR "desp_diff_queue: excluding $this_exp_id for $this_object due to being rejected $this_comment\n";
     2329#                    }
     2330#                }
     2331#                @{ $warpsBQ } = @keep_warps;
     2332#
     2333#                if ($nwarps >= 2) {
     2334#                    #one regular diff has already been made. So, need only one more. Strip a good entry from the array             
     2335#                    my $nrem = 0;
     2336#                    my @keep_warps = ();
     2337#                    foreach my $this_warp (@{ $warpsBQ }) {
     2338#                        my $this_comment = ${ $this_warp }[3];
     2339#                        my $this_exp_id  = ${ $this_warp }[0];
     2340#                        my $this_fwhm   = ${ $this_warp }[7];
     2341#                        if (($nrem <1) && ($this_fwhm <= $maxFWHM)) {
     2342#                            $nrem++;
     2343#                            print STDERR "desp_diff_queue: excluding $this_exp_id for $this_object from dirty desp diffs $this_comment\n";
     2344#                        } else {
     2345#                            push @keep_warps, $this_warp;                       
     2346#                        }
     2347#                    }
     2348#                    @{ $warpsBQ } = @keep_warps;
     2349#                }
     2350#
     2351#                # We are attempting to do the missing diffs, so reverse the list of retained warps.
     2352#                # Good objects with all visits will be skipped due to the duplicate check.
     2353#                # Bad objects will have the earliest visit rejected, and the visits repaired in a way that will produce all desired pairs.
     2354#                @{ $warpsBQ } = reverse @{ $warpsBQ };
     2355#
     2356#                # Exclude the last entry if we do not have an even number of warps.
     2357#                if (($#{ $warpsBQ } + 1) % 2 != 0) {
     2358#                    print STDERR "desp_diff_queue: Number of input warps to make dirty diffs is not even for target $target and object $this_object!";
     2359#                    my $rejected_warp = pop @{ $warpsBQ };
     2360#                    my $rejected_exp_id = ${ $rejected_warp }[0];
     2361#                    print STDERR ": Rejecting ${rejected_exp_id} to force visit count.\n";
     2362#                }
     2363#                my $nwarpsBQ = ($#{$warpsBQ} + 1);
     2364#       
     2365#               
     2366#                while ($#{ $warpsBQ } > -1) {
     2367#                    # The array is sorted in pairs of input/template.
     2368#                    my $template_warp = shift @{ $warpsBQ };
     2369#                    my $input_warp = shift @{ $warpsBQ };
     2370#   
     2371#                    my $input_exp_id = ${ $input_warp }[0];
     2372#                    my $input_comment = ${ $input_warp }[3];
     2373#
     2374#                    my $template_exp_id = ${ $template_warp }[0];
     2375#                    my $template_comment = ${ $template_warp }[3];
     2376#
     2377#                    my $input_warp_id = ${ $input_warp }[1];
     2378#                    my $template_warp_id = ${ $template_warp }[1];
     2379#
     2380#                    my $input_warp_state = ${ $input_warp }[4];
     2381#                    my $template_warp_state = ${ $template_warp }[4];
     2382#
     2383#                    my $input_warp_camQuality = ${ $input_warp }[5];
     2384#                    my $template_warp_camQuality = ${ $template_warp }[5];
     2385#
     2386#                    $Npotential++;
     2387#
     2388#                    unless (defined($input_warp_id) && defined($template_warp_id) &&
     2389#                        ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
     2390#                        print STDERR "Desp diff for this $date $target $input_exp_id $template_exp_id not fully processed ($input_warp_state $template_warp_state) ($input_warp_camQuality $template_warp_camQuality)\n";
     2391#                        if (($input_warp_camQuality == 4007)||($template_warp_camQuality == 4007)) {
     2392#                            # This should now never be reached.
     2393#                            # CZW: Trigger backup plan here?  Or simply set up framework?
     2394#                            print STDERR "  ...but this is due to a camera stage astrometry quality\n";
     2395#                            $Npotential--;
     2396#                        }
     2397#                        next;
     2398#                    }
     2399#
     2400#                    if (verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
     2401#                        $Nqueued++;
     2402#                        print STDERR "Desp diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     2403#                        next;
     2404#                    }
     2405#                    else {
     2406#                        print STDERR "Preparing to dirty diff $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment $template_comment\n";
     2407#                    }
     2408#           
     2409#                    my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
     2410#                    $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
     2411#                    $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
     2412#                    $cmd .= "-rerun "; # Needed because we may have some diffs that already use some of the exposures
     2413#                    $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
     2414#                    $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
     2415#                    if (defined($reduction)) {
     2416#                        $cmd .= " -set_reduction $reduction ";
     2417#                    }
     2418#       
     2419#                    if (defined($pretend)) {
     2420#                        $cmd .= ' -pretend ';
     2421#                    }
     2422#                    if ($debug == 1) {
     2423#                        $cmd .= ' -pretend ';
     2424#                        print STDERR "desp_diff_queue: $cmd\n";
     2425#                        print STDERR " $input_warp_id $template_warp_id\n";
     2426#                    }
     2427#           
     2428#                    if (($debug == 0)&&(!defined($pretend))) {
     2429#                        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2430#                            run ( command => $cmd, verbose => $verbose );
     2431#                        unless ($success) {
     2432#                            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2433#                            &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2434#                        }
     2435#                        $Nqueued++;
     2436#                    }
     2437#                }
    20052438           
    2006                 my $cmd = "$difftool -dbname $dbname  -definewarpwarp  ";
    2007                 $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
    2008                 $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
    2009                 $cmd .= "-rerun "; # Needed because we may have some diffs that already use some of the exposures
    2010                 $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $data_group ";
    2011                 $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
    2012 #                   $cmd .= " -pretend ";
    2013                 if (defined($reduction)) {
    2014                     $cmd .= " -set_reduction $reduction ";
    2015                 }
    2016 
    2017                 if (defined($pretend)) {
    2018                     $cmd .= ' -pretend ';
    2019                 }
    2020                 if ($debug == 1) {
    2021                     $cmd .= ' -pretend ';
    2022                     print STDERR "desp_diff_queue: $cmd\n";
    2023                     print STDERR " $input_warp_id $template_warp_id\n";
    2024                 }
    20252439           
    2026                 if (($debug == 0)&&(!defined($pretend))) {
    2027                     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2028                         run ( command => $cmd, verbose => $verbose );
    2029                     unless ($success) {
    2030                         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2031                         &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2032                     }
    2033                     $Nqueued++;
    2034                 }
    2035             }
     2440           
     2441             }
    20362442        }
    20372443    }
    20382444    $metadata_out{nsDiffPotential} += $Npotential;
    20392445    $metadata_out{nsDiffQueued}    += $Nqueued;
    2040 #      if (($metadata_out{nsDiffPotential} == $metadata_out{nsDiffQueued})&&($metadata_out{nsObservingState} eq 'END_OF_NIGHT')) {
    2041 #       $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
    2042 #      }       
    2043 
    20442446}
    20452447
     
    20612463    my $Npotential = 0;
    20622464    my $Nqueued = 0;
    2063     
     2465   
    20642466    foreach my $object_row (@{ $object_ref }) {
    2065         my $this_object = shift @{ $object_row };
    2066 #       my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment from warpRun JOIN fakeRun USING(fake_id) JOIN camRun USING(cam_id) JOIN chipRun USING(chip_id) JOIN rawExp USING(exp_id) ";
    2067 #       $input_sth .= " WHERE warpRun.state = 'full' AND warpRun.label = '$label' AND warpRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
    2068 #       $input_sth .= " ORDER BY dateobs ";
    2069        
    2070         my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state FROM ";
    2071         $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
    2072         $input_sth .=   " WHERE warpRun.label = '$label' AND warpRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
    2073         $input_sth .=   " ORDER BY dateobs ";
    2074 
    2075         my $warps = $db->selectall_arrayref( $input_sth );
    2076 
    2077         # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
    2078         my %comment_hash = ();
    2079         foreach my $this_warp (@{ $warps }) {
    2080             my $this_comment = ${ $this_warp }[3];
    2081             my $this_exp_id  = ${ $this_warp }[0];
    2082             $comment_hash{$this_comment} = $this_exp_id;
    2083         }
    2084        
    2085         if (($#{ $warps } + 1) % 2 != 0) {
    2086             print STDERR "md_diff_queue: Number of input warps to make diffs is not even for target $target and object $this_object! $#{ $warps } ";
    2087             if ($#{ $warps} + 1 == 1) {
    2088                 print STDERR ": I can do no diffs with only one exposure.\n";
    2089                 next;
    2090             }
    2091             else {
    2092                 print STDERR ": I should declare an exposure to be faulty.\n";
    2093                 my @keep_warps = ();
    2094 #               print "@{ $warps }\n";
    2095                 foreach my $this_warp (@{ $warps }) {
    2096                     my $this_comment = ${ $this_warp }[3];
    2097                     my $this_exp_id  = ${ $this_warp }[0];
    2098                     if ($comment_hash{$this_comment} == $this_exp_id) {
    2099                         push @keep_warps, $this_warp;
    2100                     }
    2101                     else {
    2102                         print STDERR "md_diff_queue: excluding $this_exp_id for $this_object\n";
    2103                     }
    2104                 }
    2105                 @{ $warps } = @keep_warps;
    2106 #               print "@{ $warps }\n";
    2107             }
    2108         }
    2109        
    2110         while ($#{ $warps } > -1) {
    2111             my $input_warp = shift @{ $warps };
    2112             my $input_exp_id = ${ $input_warp }[0];
    2113             my $input_comment = ${ $input_warp }[3];
    2114 
    2115            
    2116             my $template_warp = shift @{ $warps };
    2117 
    2118             my $template_exp_id = ${ $template_warp }[0];
    2119            
    2120             my $input_warp_id = ${ $input_warp }[1];
    2121             my $template_warp_id = ${ $template_warp }[1];
    2122 
    2123             my $input_warp_state = ${ $input_warp }[4];
    2124             my $template_warp_state = ${ $template_warp }[4];
    2125            
    2126             unless(defined($template_warp)&& defined($template_exp_id)) {
    2127                 print STDERR "md_diff received an undef! $input_exp_id $input_comment $this_object T: $template_warp V: @$template_warp\n";
    2128                 next;
    2129             }
    2130             $Npotential++;
    2131            
    2132             unless (defined($input_warp_id) && defined($template_warp_id) &&
    2133                     ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
    2134                 print STDERR "md_Diff for this $date $target $input_exp_id ($input_warp_id $input_warp_state) $template_exp_id ($template_warp_id $template_warp_state) not fully processed\n";
    2135                 next;
    2136             }
    2137 
    2138             if (multi_date_verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
    2139                 $Nqueued++;
    2140                 print STDERR "md_Diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment\n";
    2141                 next;
    2142             }
    2143 
    2144             my $new_data_group = "${data_group}.multi";
    2145             my $cmd = "$difftool -dbname $dbname  -definewarpwarp ";
    2146             $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
    2147             $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
    2148             $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $new_data_group ";
    2149             $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
    2150             if (defined($reduction)) {
    2151                 $cmd .= " -set_reduction $reduction ";
    2152             }
    2153 
    2154 #               $cmd .= " -pretend ";
    2155             if (defined($pretend)) {
    2156                 $cmd .= ' -pretend ';
    2157             }
    2158             if ($debug == 1) {
    2159                 $cmd .= ' -pretend ';
    2160                 print STDERR "md_Diffs would like to queue for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment\n";
    2161                 print STDERR "md_diff_queue: $cmd\n";
    2162                 print STDERR " $input_warp_id $template_warp_id\n";
    2163             }
    2164            
    2165             if (($debug == 0)&&(!defined($pretend))) {
    2166                 my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2167                     run ( command => $cmd, verbose => $verbose );
    2168                 unless ($success) {
    2169                     $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2170                     &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2171                 }
    2172                 $Nqueued++;
    2173             }
    2174         }
     2467        my $this_object = shift @{ $object_row };
     2468#       my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment from warpRun JOIN fakeRun USING(fake_id) JOIN camRun USING(cam_id) JOIN chipRun USING(chip_id) JOIN rawExp USING(exp_id) ";
     2469#       $input_sth .= " WHERE warpRun.state = 'full' AND warpRun.label = '$label' AND warpRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
     2470#       $input_sth .= " ORDER BY dateobs ";
     2471       
     2472        my $input_sth = "select exp_id,warp_id,dateobs,rawExp.comment,warpRun.state AS warp_state FROM ";
     2473        $input_sth .=   " rawExp LEFT JOIN chipRun USING (exp_id) LEFT JOIN camRun USING (chip_id) LEFT JOIN fakeRun USING (cam_id) LEFT JOIN warpRun USING (fake_id) ";
     2474        $input_sth .=   " WHERE warpRun.label = '$label' AND warpRun.data_group = '$data_group' AND rawExp.filter = '$filter' AND rawExp.object = '$this_object' ";
     2475        $input_sth .=   " ORDER BY dateobs ";
     2476
     2477        my $warps = $db->selectall_arrayref( $input_sth );
     2478
     2479        # Each comment should only appear once. Therefore, if we see it more than once, we assume the first is extra.
     2480        my %comment_hash = ();
     2481        foreach my $this_warp (@{ $warps }) {
     2482            my $this_comment = ${ $this_warp }[3];
     2483            my $this_exp_id  = ${ $this_warp }[0];
     2484            $comment_hash{$this_comment} = $this_exp_id;
     2485        }
     2486       
     2487        if (($#{ $warps } + 1) % 2 != 0) {
     2488            print STDERR "md_diff_queue: Number of input warps to make diffs is not even for target $target and object $this_object! $#{ $warps } ";
     2489            if ($#{ $warps} + 1 == 1) {
     2490                print STDERR ": I can do no diffs with only one exposure.\n";
     2491                next;
     2492            }
     2493            else {
     2494                print STDERR ": I should declare an exposure to be faulty.\n";
     2495                my @keep_warps = ();
     2496#               print "@{ $warps }\n";
     2497                foreach my $this_warp (@{ $warps }) {
     2498                    my $this_comment = ${ $this_warp }[3];
     2499                    my $this_exp_id  = ${ $this_warp }[0];
     2500                    if ($comment_hash{$this_comment} == $this_exp_id) {
     2501                        push @keep_warps, $this_warp;
     2502                    }
     2503                    else {
     2504                        print STDERR "md_diff_queue: excluding $this_exp_id for $this_object\n";
     2505                    }
     2506                }
     2507                @{ $warps } = @keep_warps;
     2508#               print "@{ $warps }\n";
     2509            }
     2510        }
     2511       
     2512        while ($#{ $warps } > -1) {
     2513            my $input_warp = shift @{ $warps };
     2514            my $input_exp_id = ${ $input_warp }[0];
     2515            my $input_comment = ${ $input_warp }[3];
     2516
     2517          
     2518            my $template_warp = shift @{ $warps };
     2519
     2520            my $template_exp_id = ${ $template_warp }[0];
     2521          
     2522            my $input_warp_id = ${ $input_warp }[1];
     2523            my $template_warp_id = ${ $template_warp }[1];
     2524
     2525            my $input_warp_state = ${ $input_warp }[4];
     2526            my $template_warp_state = ${ $template_warp }[4];
     2527          
     2528            unless(defined($template_warp)&& defined($template_exp_id)) {
     2529                print STDERR "md_diff received an undef! $input_exp_id $input_comment $this_object T: $template_warp V: @$template_warp\n";
     2530                next;
     2531            }
     2532            $Npotential++;
     2533          
     2534            unless (defined($input_warp_id) && defined($template_warp_id) &&
     2535                    ($input_warp_state eq 'full')&&($template_warp_state eq 'full')) {
     2536                print STDERR "md_Diff for this $date $target $input_exp_id ($input_warp_id $input_warp_state) $template_exp_id ($template_warp_id $template_warp_state) not fully processed\n";
     2537                next;
     2538            }
     2539
     2540            if (multi_date_verify_uniqueness_diff($input_warp_id,$template_warp_id,$date,$target) != 0) {
     2541                $Nqueued++;
     2542                print STDERR "md_Diffs already queued for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment\n";
     2543                next;
     2544            }
     2545
     2546            my $new_data_group = "${data_group}.multi";
     2547            my $cmd = "$difftool -dbname $dbname  -definewarpwarp ";
     2548            $cmd .= "-input_label $label  -template_label $label -good_frac 0.1 ";
     2549            $cmd .= "-backwards "; # Needed because difftool assumes a different date sorting.
     2550            $cmd .= "-set_workdir $workdir  -set_dist_group $dist_group  -set_data_group $new_data_group ";
     2551            $cmd .= " -simple  -set_label $label -exp_id $input_exp_id -template_exp_id $template_exp_id ";
     2552            if (defined($reduction)) {
     2553                $cmd .= " -set_reduction $reduction ";
     2554            }
     2555
     2556#               $cmd .= " -pretend ";
     2557            if (defined($pretend)) {
     2558                $cmd .= ' -pretend ';
     2559            }
     2560            if ($debug == 1) {
     2561                $cmd .= ' -pretend ';
     2562                print STDERR "md_Diffs would like to queue for this $date $target $input_exp_id $template_exp_id ($input_warp_id $template_warp_id) $this_object $input_comment\n";
     2563                print STDERR "md_diff_queue: $cmd\n";
     2564                print STDERR " $input_warp_id $template_warp_id\n";
     2565            }
     2566          
     2567            if (($debug == 0)&&(!defined($pretend))) {
     2568                my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2569                    run ( command => $cmd, verbose => $verbose );
     2570                unless ($success) {
     2571                    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2572                    &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2573                }
     2574                $Nqueued++;
     2575            }
     2576        }
    21752577    }
    21762578    $metadata_out{nsDiffPotential} += $Npotential;
    21772579    $metadata_out{nsDiffQueued}    += $Nqueued;
    21782580#      if (($metadata_out{nsDiffPotential} == $metadata_out{nsDiffQueued})&&($metadata_out{nsObservingState} eq 'END_OF_NIGHT')) {
    2179      $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
    2180 #      }       
     2581     $metadata_out{nsDiffState} = 'FINISHED_DIFFS';
     2582#      }       
    21812583
    21822584}
     
    21972599
    21982600
    2199 # Get a list of exposures that could be diffed    
     2601# Get a list of exposures that could be diffed   
    22002602    my $new_data_group = "${data_group}.offnight";
    22012603    my $new_dist_group = "${dist_group}.offnight";
     
    22072609    $check_cmd .= " -dateobs_begin ${lunation_start}T00:00:00 -dateobs_end ${lunation_end}T23:59:59 -distance 1.5 ";
    22082610    if (defined($reduction)) {
    2209         $check_cmd .= " -set_reduction $reduction ";
     2611        $check_cmd .= " -set_reduction $reduction ";
    22102612    }
    22112613
    22122614    my ($success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2213         run ( command => $check_cmd, verbose => $verbose );
     2615        run ( command => $check_cmd, verbose => $verbose );
    22142616    unless ($success) {
    2215         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2216         &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2217     }
    2218     
     2617        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2618        &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2619    }
     2620   
    22192621    # Parse results
    22202622    my $diffs = $mdcParser->parse_list(join "", @$stdout_buf) or
    2221         &my_die("Unable to parse metadata from difftool -definewarpwarp", 0, 0, $date, $PS_EXIT_PROG_ERROR);
     2623        &my_die("Unable to parse metadata from difftool -definewarpwarp", 0, 0, $date, $PS_EXIT_PROG_ERROR);
    22222624    foreach my $diff (@$diffs) {
    2223         unless (multi_date_verify_uniqueness_diff($diff->{input_warp_id},$diff->{template_warp_id},$date,$target)) {
    2224             # If we don't already have a diff with these inputs, make a diff with these inputs.
    2225             my $cmd = "$difftool -dbname $dbname -definewarpwarp -good_frac 0.1 ";
    2226             $cmd   .= "-input_label $label -template_label $label ";
    2227             $cmd   .= "-warp_id $diff->{input_warp_id} -template_warp_id $diff->{template_warp_id} ";
    2228             $cmd .= "-set_workdir $workdir  -set_dist_group $new_dist_group  -set_data_group $new_data_group ";
    2229             $cmd .= " -mintimediff 40000 ";
    2230             $cmd .= " -simple  -rerun -set_label $label -filter $filter ";
    2231             $cmd .= " -dateobs_begin ${lunation_start}T00:00:00 -dateobs_end ${lunation_end}T23:59:59 -distance 1.5 ";
    2232             if (defined($reduction)) {
    2233                 $cmd .= " -set_reduction $reduction ";
    2234             }
    2235 
    2236             if (defined($pretend)) {
    2237                 $cmd .= ' -pretend ';
    2238             }
    2239             print STDERR "ON_diffs wants to run this command: $cmd\n";
    2240            
    2241             if (($debug == 0)&&(!defined($pretend))) {
    2242                 my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2243                     run ( command => $cmd, verbose => $verbose );
    2244                 unless ($success) {
    2245                     $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2246                     &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2247                 }
    2248             }
    2249         }
     2625        unless (multi_date_verify_uniqueness_diff($diff->{input_warp_id},$diff->{template_warp_id},$date,$target)) {
     2626            # If we don't already have a diff with these inputs, make a diff with these inputs.
     2627            my $cmd = "$difftool -dbname $dbname -definewarpwarp -good_frac 0.1 ";
     2628            $cmd   .= "-input_label $label -template_label $label ";
     2629            $cmd   .= "-warp_id $diff->{input_warp_id} -template_warp_id $diff->{template_warp_id} ";
     2630            $cmd .= "-set_workdir $workdir  -set_dist_group $new_dist_group  -set_data_group $new_data_group ";
     2631            $cmd .= " -mintimediff 40000 ";
     2632            $cmd .= " -simple  -rerun -set_label $label -filter $filter ";
     2633            $cmd .= " -dateobs_begin ${lunation_start}T00:00:00 -dateobs_end ${lunation_end}T23:59:59 -distance 1.5 ";
     2634            if (defined($reduction)) {
     2635                $cmd .= " -set_reduction $reduction ";
     2636            }
     2637
     2638            if (defined($pretend)) {
     2639                $cmd .= ' -pretend ';
     2640            }
     2641            print STDERR "ON_diffs wants to run this command: $cmd\n";
     2642          
     2643            if (($debug == 0)&&(!defined($pretend))) {
     2644                my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2645                    run ( command => $cmd, verbose => $verbose );
     2646                unless ($success) {
     2647                    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2648                    &my_die("Unable to perform difftool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2649                }
     2650            }
     2651        }
    22502652    }
    22512653}
     
    22612663    my ($stacks_to_finish,$stacks_total) = check_stack_count($label);
    22622664    if (($stacks_to_finish == 0)&&($stacks_total != 0)) {
    2263         my $cmd = "$difftool -dbname $dbname -definewarpstack ";
    2264         $cmd .= " -good_frac 0.2 ";
    2265         $cmd .= " -warp_label $label -stack_label $label -set_label $label ";
    2266         $cmd .= " -set_workdir $workdir -available -set_reduction WARPSTACK -set_dist_group $dist_group ";
    2267         $cmd .= " -rerun ";
    2268     }
    2269 }          
     2665        my $cmd = "$difftool -dbname $dbname -definewarpstack ";
     2666        $cmd .= " -good_frac 0.2 ";
     2667        $cmd .= " -warp_label $label -stack_label $label -set_label $label ";
     2668        $cmd .= " -set_workdir $workdir -available -set_reduction WARPSTACK -set_dist_group $dist_group ";
     2669        $cmd .= " -rerun ";
     2670    }
     2671}          
    22702672
    22712673sub check_stack_count {
     
    22982700    my $retention_time;
    22992701    if (exists($science_config{$target}{$mode})) {
    2300         $retention_time = $science_config{$target}{$mode};
     2702        $retention_time = $science_config{$target}{$mode};
    23012703    }
    23022704    else {
    2303         $retention_time = $clean_config{$mode}{RETENTION_TIME};
     2705        $retention_time = $clean_config{$mode}{RETENTION_TIME};
    23042706    }
    23052707    if ($retention_time <= 0) {
    2306         return("no clean","true");
     2708        return("no clean","true");
    23072709    }
    23082710
    23092711    my ($year,$month,$day) = split /-/,$date;
    23102712    my $dt = DateTime->new(year => $year, month => $month, day => $day,
    2311                            hour => 0, minute => 0, second => 0, nanosecond => 0,
    2312                            time_zone => 'Pacific/Honolulu');
    2313        
     2713                           hour => 0, minute => 0, second => 0, nanosecond => 0,
     2714                           time_zone => 'Pacific/Honolulu');
     2715       
    23142716    $dt->subtract(days => $retention_time);
    23152717    my $cleaning_date = $dt->ymd;
    23162718
    23172719    my ($label,$workdir,$obs_mode,$object,$comment,$tess_id,$dist_group,$data_group,$reduction) = get_tool_parameters($cleaning_date,$target);
    2318     
     2720   
    23192721    $command =~ s/\@DBNAME\@/$dbname/;
    23202722    $command =~ s/\@LABEL\@/$label/;
     
    23272729    $command =~ s/\@REDUCTION\@/$reduction/;
    23282730    $command =~ s/\@CURRENT_DATE\@/$cleaning_date/;
    2329     
     2731   
    23302732    if ($debug == 1) {
    23312733        $command .= ' -pretend ';
     
    23392741
    23402742    foreach my $mode (sort (keys %clean_config)) {
    2341         foreach my $target (sort (keys %science_config)) {
    2342             if (exists($science_config{$target}{NOCLEAN})) {
    2343                 next;
    2344             }
    2345             my ($cleaning_date,$command) = construct_cleantool_args($date,$target,$mode);
    2346 
    2347             if ($cleaning_date eq 'no clean') {
    2348                 next;
    2349             }           
    2350             print STDERR "$command\n";
    2351             if (!(defined($pretend) || $debug == 1)) {
     2743        foreach my $target (sort (keys %science_config)) {
     2744            if (exists($science_config{$target}{NOCLEAN})) {
     2745                next;
     2746            }
     2747            my ($cleaning_date,$command) = construct_cleantool_args($date,$target,$mode);
     2748
     2749            if ($cleaning_date eq 'no clean') {
     2750                next;
     2751            }           
     2752            print STDERR "$command\n";
     2753            if (!(defined($pretend) || $debug == 1)) {
    23522754#           print STDERR "BEAR IS DRIVING!?\n";
    2353                 my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2354                     run ( command => $command, verbose => $verbose );
    2355                 unless ($success) {
    2356                     $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2357                     &my_die("Unable to perform cleantool ($command): $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2358                 }
    2359                 add_to_macro_list('clean_old',1,$date,$target,$mode);
    2360             }
    2361             if ($mode eq 'DIFF') {
    2362                 my $WS_command = $command;
    2363                 $WS_command =~ s/$target/${target}.WS/;
    2364                 print STDERR "$WS_command\n";
    2365                 if (!(defined($pretend) || $debug == 1)) {
    2366                    
    2367                     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2368                         run ( command => $WS_command, verbose => $verbose );
    2369                     unless ($success) {
    2370                         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2371                         &my_die("Unable to perform cleantool ($WS_command): $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2372                     }
    2373                 }
    2374             }
    2375 
    2376         }
     2755                my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2756                    run ( command => $command, verbose => $verbose );
     2757                unless ($success) {
     2758                    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2759                    &my_die("Unable to perform cleantool ($command): $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2760                }
     2761                add_to_macro_list('clean_old',1,$date,$target,$mode);
     2762            }
     2763            if ($mode eq 'DIFF') {
     2764                my $WS_command = $command;
     2765                $WS_command =~ s/$target/${target}.WS/;
     2766                print STDERR "$WS_command\n";
     2767                if (!(defined($pretend) || $debug == 1)) {
     2768                  
     2769                    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2770                        run ( command => $WS_command, verbose => $verbose );
     2771                    unless ($success) {
     2772                        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2773                        &my_die("Unable to perform cleantool ($WS_command): $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2774                    }
     2775                }
     2776            }
     2777
     2778        }
    23772779    }
    23782780    return(0);
     
    23862788    my $date = shift;
    23872789    my $eon_dt = DateTime->new( year   => $datetime->year,
    2388                                 month  => $datetime->month,
    2389                                 day    => $datetime->day,
    2390                                 hour   => 17, # 7,
    2391                                 minute => 30,
    2392                                 second => 0,
    2393                                 time_zone => 'UTC');
    2394     
     2790                                month  => $datetime->month,
     2791                                day    => $datetime->day,
     2792                                hour   => 17, # 7,
     2793                                minute => 30,
     2794                                second => 0,
     2795                                time_zone => 'UTC');
     2796   
    23952797    foreach my $eon (keys %eon_config) {
    2396         my $command = "$regtool -processedexp -simple ";
    2397         $command .= " -dbname $dbname ";
    2398         $command .= " -dateobs_begin ${date}T00:00:00 -dateobs_end ${date}T23:59:59 ";
    2399         $command .= " -object $eon_config{$eon}{OBJECT} " if defined($eon_config{$eon}{OBJECT});
    2400         $command .= " -obs_mode $eon_config{$eon}{OBSMODE} " if defined($eon_config{$eon}{OBSMODE});
    2401         $command .= " -exp_type $eon_config{$eon}{EXPTYPE} " if defined($eon_config{$eon}{EXPTYPE});
    2402         $command .= " -comment $eon_config{$eon}{COMMENT} " if defined($eon_config{$eon}{COMMENT});
    2403 
    2404         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2405             run ( command => $command, verbose => $verbose );
    2406         unless ($success) {
    2407             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2408             &my_die("Unable to perform regtool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2409         }
    2410         my @eon_exposures = split /\n/, (join '', @$stdout_buf);
    2411         if ($#eon_exposures >= 0) {
    2412             return("END_OF_NIGHT");
    2413         }
    2414     }   
     2798        my $command = "$regtool -processedexp -simple ";
     2799        $command .= " -dbname $dbname ";
     2800        $command .= " -dateobs_begin ${date}T00:00:00 -dateobs_end ${date}T23:59:59 ";
     2801        $command .= " -object $eon_config{$eon}{OBJECT} " if defined($eon_config{$eon}{OBJECT});
     2802        $command .= " -obs_mode $eon_config{$eon}{OBSMODE} " if defined($eon_config{$eon}{OBSMODE});
     2803        $command .= " -exp_type $eon_config{$eon}{EXPTYPE} " if defined($eon_config{$eon}{EXPTYPE});
     2804        $command .= " -comment $eon_config{$eon}{COMMENT} " if defined($eon_config{$eon}{COMMENT});
     2805
     2806        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2807            run ( command => $command, verbose => $verbose );
     2808        unless ($success) {
     2809            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2810            &my_die("Unable to perform regtool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2811        }
     2812        my @eon_exposures = split /\n/, (join '', @$stdout_buf);
     2813        if ($#eon_exposures >= 0) {
     2814            return("END_OF_NIGHT");
     2815        }
     2816    }   
    24152817    if ($force_registration) {
    2416         return("END_OF_NIGHT");
     2818        return("END_OF_NIGHT");
    24172819    }
    24182820#    print "$now $eon_dt " . DateTime->compare($now,$eon_dt) . "\n";
    24192821    if (DateTime->compare($now,$eon_dt) < 1) {
    2420         return("OBSERVING");
     2822        return("OBSERVING");
    24212823    }
    24222824    else {
    2423         return("END_OF_NIGHT");
     2825        return("END_OF_NIGHT");
    24242826    }
    24252827}
     
    24302832
    24312833    foreach my $eon (keys %eon_config) {
    2432         my $command = "$regtool -processedexp -simple ";
    2433         $command .= " -dbname $dbname ";
    2434         $command .= " -dateobs_begin ${date}T00:00:00 -dateobs_end ${date}T23:59:59 ";
    2435         $command .= " -object $eon_config{$eon}{OBJECT} " if defined($eon_config{$eon}{OBJECT});
    2436         $command .= " -obs_mode $eon_config{$eon}{OBSMODE} " if defined($eon_config{$eon}{OBSMODE});
    2437         $command .= " -exp_type $eon_config{$eon}{EXPTYPE} " if defined($eon_config{$eon}{EXPTYPE});
    2438         $command .= " -comment $eon_config{$eon}{COMMENT} " if defined($eon_config{$eon}{COMMENT});
    2439 
    2440         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    2441             run ( command => $command, verbose => $verbose );
    2442         unless ($success) {
    2443             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    2444             &my_die("Unable to perform regtool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
    2445         }
    2446         my @eon_exposures = split /\n/, (join '', @$stdout_buf);
    2447         if ($#eon_exposures >= 0) {
    2448             return("REGISTERED");
    2449         }
    2450     }   
     2834        my $command = "$regtool -processedexp -simple ";
     2835        $command .= " -dbname $dbname ";
     2836        $command .= " -dateobs_begin ${date}T00:00:00 -dateobs_end ${date}T23:59:59 ";
     2837        $command .= " -object $eon_config{$eon}{OBJECT} " if defined($eon_config{$eon}{OBJECT});
     2838        $command .= " -obs_mode $eon_config{$eon}{OBSMODE} " if defined($eon_config{$eon}{OBSMODE});
     2839        $command .= " -exp_type $eon_config{$eon}{EXPTYPE} " if defined($eon_config{$eon}{EXPTYPE});
     2840        $command .= " -comment $eon_config{$eon}{COMMENT} " if defined($eon_config{$eon}{COMMENT});
     2841
     2842        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     2843            run ( command => $command, verbose => $verbose );
     2844        unless ($success) {
     2845            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     2846            &my_die("Unable to perform regtool: $error_code", 0,0,$date, $PS_EXIT_SYS_ERROR);
     2847        }
     2848        my @eon_exposures = split /\n/, (join '', @$stdout_buf);
     2849        if ($#eon_exposures >= 0) {
     2850            return("REGISTERED");
     2851        }
     2852    }   
    24512853    return("NOT_REGISTERED");
    24522854}
    24532855
    2454     
     2856   
    24552857
    24562858sub get_tool_parameters {
     
    24862888    my $internal_filter;
    24872889    if (defined($det_filter)) {
    2488         $internal_filter = $det_filter; $internal_filter =~ s/\..*//;
    2489         $internal_filter = '.' . $internal_filter;
     2890        $internal_filter = $det_filter; $internal_filter =~ s/\..*//;
     2891        $internal_filter = '.' . $internal_filter;
    24902892    }
    24912893    else {
    2492         $internal_filter = '';
     2894        $internal_filter = '';
    24932895    }
    24942896    unless (defined($maxN)) {
    2495         $maxN = 0;
     2897        $maxN = 0;
    24962898    }
    24972899    my $lc_type = lc($exp_type);
     
    25092911
    25102912    if ((defined($macro_config{$proc_mode}))&&($do_or_do_not)) {
    2511         unless (defined($metadata_out{N_MACROS})) {
    2512             $metadata_out{N_MACROS} = 0;
    2513         }
    2514         my $N = $metadata_out{N_MACROS};
    2515         $metadata_out{"ns${N}Macro"} = $macro_config{$proc_mode};
    2516         if ($debug == 1) {
    2517             print STDERR "WORKING ON A MACRO: ns${N}Macro $proc_mode $macro_config{$proc_mode}\n";
    2518         }
    2519         if (defined($date)&&(defined($target))) {
    2520 
    2521             my ($label,$workdir,$obs_mode,$object,$comment,$tess_id,$dist_group,$data_group,$reduction)
    2522                 = get_tool_parameters($date,$target);
    2523             $metadata_out{"ns${N}Macro"} =~ s/\@LABEL\@/$label/;
    2524             $metadata_out{"ns${N}Macro"} =~ s/\@WORKDIR\@/$workdir/;
    2525             $metadata_out{"ns${N}Macro"} =~ s/\@OBSMODE\@/$obs_mode/;
    2526             $metadata_out{"ns${N}Macro"} =~ s/\@OBJECT\@/$object/;
    2527             $metadata_out{"ns${N}Macro"} =~ s/\@COMMENT\@/$comment/;
    2528             $metadata_out{"ns${N}Macro"} =~ s/\@TESS_ID\@/$tess_id/;
    2529             $metadata_out{"ns${N}Macro"} =~ s/\@DIST_GROUP\@/$dist_group/;
    2530             $metadata_out{"ns${N}Macro"} =~ s/\@DATA_GROUP\@/$data_group/;
    2531             $metadata_out{"ns${N}Macro"} =~ s/\@REDUCTION\@/$reduction/;
    2532         }
    2533         if (defined($mode)) {
    2534             $metadata_out{"ns${N}Macro"} =~ s/\@EXTRA\@/$mode/;
    2535         }
    2536         if (defined($date)) {
    2537             $metadata_out{"ns${N}Macro"} =~ s/\@DATE\@/$date/;
    2538         }
    2539         if ($debug == 1) {
    2540             print STDERR "DONE WITH A MACRO: ns${N}Macro $proc_mode $macro_config{$proc_mode}\n";
    2541         }
    2542         $metadata_out{N_MACROS} ++;
     2913        unless (defined($metadata_out{N_MACROS})) {
     2914            $metadata_out{N_MACROS} = 0;
     2915        }
     2916        my $N = $metadata_out{N_MACROS};
     2917        $metadata_out{"ns${N}Macro"} = $macro_config{$proc_mode};
     2918        if ($debug == 1) {
     2919            print STDERR "WORKING ON A MACRO: ns${N}Macro $proc_mode $macro_config{$proc_mode}\n";
     2920        }
     2921        if (defined($date)&&(defined($target))) {
     2922
     2923            my ($label,$workdir,$obs_mode,$object,$comment,$tess_id,$dist_group,$data_group,$reduction)
     2924                = get_tool_parameters($date,$target);
     2925            $metadata_out{"ns${N}Macro"} =~ s/\@LABEL\@/$label/;
     2926            $metadata_out{"ns${N}Macro"} =~ s/\@WORKDIR\@/$workdir/;
     2927            $metadata_out{"ns${N}Macro"} =~ s/\@OBSMODE\@/$obs_mode/;
     2928            $metadata_out{"ns${N}Macro"} =~ s/\@OBJECT\@/$object/;
     2929            $metadata_out{"ns${N}Macro"} =~ s/\@COMMENT\@/$comment/;
     2930            $metadata_out{"ns${N}Macro"} =~ s/\@TESS_ID\@/$tess_id/;
     2931            $metadata_out{"ns${N}Macro"} =~ s/\@DIST_GROUP\@/$dist_group/;
     2932            $metadata_out{"ns${N}Macro"} =~ s/\@DATA_GROUP\@/$data_group/;
     2933            $metadata_out{"ns${N}Macro"} =~ s/\@REDUCTION\@/$reduction/;
     2934        }
     2935        if (defined($mode)) {
     2936            $metadata_out{"ns${N}Macro"} =~ s/\@EXTRA\@/$mode/;
     2937        }
     2938        if (defined($date)) {
     2939            $metadata_out{"ns${N}Macro"} =~ s/\@DATE\@/$date/;
     2940        }
     2941        if ($debug == 1) {
     2942            print STDERR "DONE WITH A MACRO: ns${N}Macro $proc_mode $macro_config{$proc_mode}\n";
     2943        }
     2944        $metadata_out{N_MACROS} ++;
    25432945    }
    25442946}
Note: See TracChangeset for help on using the changeset viewer.