#!/usr/bin/env perl
#----------------------------------------------------------------------------
#
# Name: update_control_tables
#
# This perl script verifies updates five CONTRL tables: dataset_link, gsa_data,
# jitter_evt_map, product_status, and product_eng_map. It inserts records into
# these tables that are used to control the FGS and AST pipelines. It uses
# the following input tables:
#
#     file_times
#     qolink_sms
#     msc_events
#     eng_dataset_pads
#     spss_db..qolink
#     spss_db..qexposure
#
# During processing the following temporary tables are created and dropped 
# at the end of processing.
#
#    #observ          for session db1
#    #datasets        for session db1
#    #acq_times       for session db2
#
#
# Restrictions:
#   The UPDATR and MSCXTR processes must have been run for the MSC file so that
#   the qolink_sms and msc_events tables have been updated.
#
# Interactive Usage:
#	>update_control_tables.pl pod_name
#
#	Note that the following environment variables (logicals) are 
#       always required: DSQUERY, SPSS_DB and OPUS_DB.
#
#
# History:
# Date     OPR      Who         Reason
# -------- -------- ----------  ---------------------------------------------
# 05/30/01 43327    Baum        Initial code
# 04/29/02 45738    Baum        Use external subroutines.
# 10/22/02 46785    Baum        Skip pre-replan gsa_data
# 11/12/02 46667    Baum        Support EPC generation by adding EPC records
#                               to product_eng_map and product_status.  
# 02/13/03 47570    Baum        Change exit status values
# 02/20/04 50403    Baum        Parameterize MAX_GSA_DURATION_MIN and use ENV
# 07/21/04 51607    Baum        Do not generate EPC records for STIS MAMA
# 02/11/09 61920    MSwam       Split create/update query into 2 after
#                                 Sybase EBF 15959 apparently altered result
# 03/25/10 64274    MSwam     Replace ST_DBlib with DBI
# 06/30/10 64432    MSwam     Use single quotes for SQLServer
#----------------------------------------------------------------------------
# set up external routines
unshift @INC,(split /:/, $ENV{PATH});
require 'printmsg.pl';       # prints a formatted status message
require 'sogs_time_pkg.pl';  # manipulate time in SOGS format(yyy.ddd:hh:mm:ss) 
require 'do_dbi_pkg.pl';     # database access
#----------------------------------------------------------------------------

#specify exit status values and other constants

    $PROCESS_FAILURE = 7; # exit status for XPOLL
    $PROCESS_SUCCESS = 9; # exit status for XPOLL
    $MAX_GSA_DURATION_MIN_DEF = 16; # default of max minutes to search for 
                                    # GS acq success

#check for arguments

    $num_arg = scalar @ARGV;

    if ($num_arg > 0 && substr($ARGV[0],0,1) ne "-") {
        $POD_FILE = $ARGV[0];
    } else {
        $POD_FILE = $ENV{"OSF_DATASET"};
    }
    if ( !defined($POD_FILE)) {
       PrintMsg ("E","Missing POD name in args or environment");
       exit( $PROCESS_FAILURE);
    } 

# get the required external variables

    $DSQUERY=           $ENV{"DSQUERY"};
    $OPUS_DB=           lc($ENV{"OPUS_DB"});
    $SPSS_DB=           lc($ENV{"SPSS_DB"});

# begin processing

    PrintMsg ("I","--- start --- Update Control Tables ----------");
    PrintMsg ("I","--- POD: $POD_FILE");

# get the optional external variable
    $MAX_GSA_DURATION_MIN = $ENV{"MAX_GSA_MINUTES"};
    
    if (!defined($MAX_GSA_DURATION_MIN)) {
      $MAX_GSA_DURATION_MIN = $MAX_GSA_DURATION_MIN_DEF;
      PrintMsg("I","ENV.MAX_GSA_MINUTES not found - ".
        "using $MAX_GSA_DURATION_MIN_DEF by default.");
    }
#---------------------------------------------------------------------
# open database for queries
#---------------------------------------------------------------------
    $db = DoDBIopen( $DSQUERY, $OPUS_DB, $PROCESS_FAILURE);

#---------------------------------------------------------------------
#  Use file_times table to get true time range of SMS. Always use the
#  replan time and report an info message if the replan time is not
#  equal to the start time.
#---------------------------------------------------------------------
    $pod_name = uc( $POD_FILE );  # use uppercased name for query

$query = <<"EOQ";
SELECT window_start, window_stop, replan_time 
FROM file_times
WHERE dataset_name = '$pod_name' and archclass = 'MSC'
EOQ
    @in_record = DoDBIselect( $db, $query );
    if ( ( scalar @in_record ) == 0 ) {
        PrintMsg( "E", "Missing file_times record for MSC $pod_name." );
        exit($PROCESS_FAILURE);
    }
    $window_start = $in_record[0];
    $window_stop  = $in_record[1];
    $replan_time  = $in_record[2];
    $sms_start = DecompressTime( $in_record[2] );
    $sms_stop  = DecompressTime( $in_record[1] );
    $old_start = DecompressTime( $in_record[0] );
    if ($sms_start ne $old_start) {
      PrintMsg ("I","Replan SMS found. Original start is $old_start.");
    }
    PrintMsg ("I","Start: $sms_start  End: $sms_stop.");
#---------------------------------------------------------------------
# Create temp table #observ from qolink_sms, qexposure, and executed
#---------------------------------------------------------------------

$query = <<"EOQ";
SELECT o.program_id program_id,o.obset_id obset_id,o.ob_number ob_number,
       o.inst inst,o.start_time start_time,o.end_time end_time,e.type type,
       x.coord_id
INTO #observ
FROM  qolink_sms o, executed x, $SPSS_DB..qolink l, $SPSS_DB..qexposure e
WHERE o.start_time>'$sms_start'
  and o.start_time<'$sms_stop'
  and o.program_id = x.program_id 
  and o.obset_id = x.obset_id 
  and o.ob_number = x.ob_number 
  and o.program_id = l.program_id 
  and o.obset_id = l.obset_id 
  and o.ob_number = l.ob_number 
  and l.proposal_id = e.proposal_id
  and l.obset_id = e.obset_id
  and l.alignment_id = e.alignment_id
  and l.exposure_id = e.exposure_id
  and l.version_num = e.version_num
EOQ
    $count = DoDBI( $db, $query );
    PrintMsg ("I","$count observations put into #observ.");
#---------------------------------------------------------------------
#  create index and change inst values for astrometry
#---------------------------------------------------------------------

$query = <<"EOQ";
CREATE UNIQUE CLUSTERED INDEX #observ_1 
ON #observ (program_id,obset_id,ob_number)
EOQ
    $count = DoDBI( $db, $query );

$query = <<"EOQ";
UPDATE #observ SET inst='F' WHERE inst IN ('1','2','3')
EOQ
    $count = DoDBI( $db, $query );
    PrintMsg("I", "$count astrometry datasets found in #observ.");

#---------------------------------------------------------------------
# Get $acq_start_time for start of search for GS acqusitions
#---------------------------------------------------------------------
    if ($replan_time > $window_start) {
      # this is a replan get first observation time
$query = <<"EOQ";
SELECT MIN(start_time)
FROM #observ
EOQ
      PrintMsg("I", "Begin replan query for first observation time.");
      @in_record = DoDBIselect( $db, $query );
      if ( (scalar @in_record ) == 0 ) {
        PrintMsg("E", "Cannot get first observation time in #observ");
        $acq_start_time = $old_start;
      }
      else {
        $first_obs_time = $in_record[0];

$query = <<"EOQ";
SELECT MAX(event_time)
FROM msc_events
WHERE event_type = 'FGS' and event_class='BOA' and event_name != 'GSACQ2'
  and event_time > '$old_start' and event_time < '$first_obs_time' 
EOQ
        PrintMsg("I", "Begin query for replan acquisition time.");
        @in_record = DoDBIselect( $db, $query );
        if ( (scalar @in_record ) == 0 ) {
          PrintMsg("E", "Cannot get start time of gsacq before replan.");
          $acq_start_time = $old_start;
        }
        else {
          $acq_start_time = $in_record[0];
        }
      }
    } else {
      $acq_start_time = $old_start;
    }

#---------------------------------------------------------------------
# Create temp table #datasets 
#---------------------------------------------------------------------

$query = <<"EOQ";
SELECT (o.inst+o.program_id+o.obset_id+o.ob_number+'J') dataset_rootname, 
   'FGS' dataset_type, o.program_id, o.obset_id, o.ob_number, o.inst,
   o.coord_id
INTO #datasets
FROM  #observ o
EOQ
    $count = DoDBI( $db, $query );
    PrintMsg ("I","$count datasets put into #datasets.");

$query = <<"EOQ";
INSERT INTO #datasets
SELECT (o.inst+o.program_id+o.obset_id+o.ob_number+'M') dataset_rootname,
   'AST' dataset_type, o.program_id, o.obset_id, o.ob_number, o.inst,
   o.coord_id
FROM  #observ o
WHERE o.inst='F'
EOQ
    $count = DoDBI( $db, $query );
    PrintMsg ("I","$count more datasets put into #datasets.");

$query = <<"EOQ";
SELECT COUNT(*) from #datasets
EOQ
    @count = DoDBIselect( $db, $query );
    PrintMsg ("I","$count[0] total rows now in #datasets.");

#---------------------------------------------------------------------
#  Open second DB session to create #acq_times and use this table
#---------------------------------------------------------------------
    $db2 = DoDBIopen( $DSQUERY, $OPUS_DB, $PROCESS_FAILURE);

#---------------------------------------------------------------------
# get GS acquisition start and end times into #acq_times - create index
# - also get first and last acq time for use in jitter_evt_map processing.
#---------------------------------------------------------------------

$query = <<"EOQ";
SELECT  event_time, event_class, event_name, 
('G'+SUBSTRING(event_time,1,4)+SUBSTRING(event_time,6,3)
           +SUBSTRING(event_time,10,2)+SUBSTRING(event_time,13,2)
           +SUBSTRING(event_time,16,2)) gsa_rootname
INTO #acq_times
FROM msc_events
WHERE event_type = 'FGS' and event_class in ('BOA','EOA') 
  and event_time >= '$acq_start_time' and event_time < '$sms_stop' 
EOQ
    $count = DoDBI( $db2, $query );
    PrintMsg ("I","$count records put into #acq_times.");

    if ($count > 0) {

$query = <<"EOQ";
CREATE UNIQUE CLUSTERED INDEX #acq_times_1 
ON #acq_times (event_time, event_class, event_name)
EOQ
      DoDBI( $db2, $query);

$query = <<"EOQ";
SELECT MIN(event_time), MAX(event_time)
FROM #acq_times
WHERE event_class='BOA' and event_name != 'GSACQ2'
EOQ
      PrintMsg("I", "Begin query for acquisition time range.");
      @in_record = DoDBIselect( $db2, $query );
      if ( ( scalar @in_record ) == 0 ) {
          PrintMsg("E", "Cannot get first and last gsacq time.");
      }
      else {
          $first_acq_time = $in_record[0];
          $last_acq_time  = $in_record[1];
      }
    }
    if (!defined($first_acq_time)) {
      $first_acq_time = $sms_stop;
      $last_acq_time = $sms_stop;
    }
#---------------------------------------------------------------------
#  Cleanup any old control records that might cause duplicate record errors
#---------------------------------------------------------------------

$query = <<"EOQ";
DELETE gsa_data 
WHERE gsa_rootname > 'G$replan_time' and gsa_rootname < 'G$window_stop'
EOQ

    $count = DoDBI( $db, $query);
    PrintMsg("I", "$count old records deleted from gsa_data.");

$query = <<"EOQ";
DELETE product_status 
WHERE product_type = 'GSA' and product_rootname > 'G$replan_time' and 
  product_rootname < 'G$window_stop'
EOQ

    $count = DoDBI( $db, $query);
    PrintMsg("I", "$count old GSA records deleted from product_status.");

$query = <<"EOQ";
DELETE product_eng_map 
WHERE product_type = 'GSA' and product_rootname > 'G$replan_time' and 
  product_rootname < 'G$window_stop'
EOQ

    $count = DoDBI( $db, $query);
    PrintMsg("I", "$count old GSA records deleted from product_eng_map.");

$query = <<"EOQ";
DELETE dataset_link 
FROM dataset_link,#datasets 
WHERE 
  dataset_link.dataset_rootname = #datasets.dataset_rootname
EOQ

    $count = DoDBI( $db, $query);
    PrintMsg("I", "$count old records deleted from dataset_link.");

$query = <<"EOQ";
DELETE jitter_evt_map 
FROM jitter_evt_map,#datasets
WHERE 
  jitter_evt_map.program_id = #datasets.program_id and
  jitter_evt_map.obset_id = #datasets.obset_id and
  jitter_evt_map.ob_number = #datasets.ob_number
  and #datasets.dataset_type = 'FGS'
EOQ

    $count = DoDBI( $db, $query);
    PrintMsg("I", "$count old records deleted from jitter_evt_map.");

$query = <<"EOQ";
DELETE product_eng_map
FROM product_eng_map,#datasets
WHERE 
  product_eng_map.product_rootname = #datasets.dataset_rootname
EOQ

    $count = DoDBI( $db, $query);
    PrintMsg("I", "$count old dataset records deleted from product_eng_map.");

$query = <<"EOQ";
DELETE product_status
FROM product_status,#datasets
WHERE 
  product_status.product_rootname = #datasets.dataset_rootname
EOQ

    $count = DoDBI( $db, $query);
    PrintMsg("I", "$count old dataset records deleted from product_status.");

#---------------------------------------------------------------------
# if not replan, then map datasets to SMS event
#---------------------------------------------------------------------
    if ($old_start eq $sms_start) {

# SQLserver will fail an INSERT that attempts to load a string with more
#   chars than the field definition.  Sybase apparently would truncate.
#   We have to explicitly truncate now, since the SMS start has subseconds.
#
$jstart = substr($sms_start,0,17);

$query = <<"EOQ";
INSERT INTO jitter_evt_map
SELECT '$jstart','SMS',o.program_id,o.obset_id,o.ob_number,'Y'
FROM #observ o
WHERE  o.start_time > '$sms_start' and o.start_time < '$first_acq_time'
  and o.type = 'CAL'
UNION
SELECT '$jstart','SMS',o.program_id,o.obset_id,o.ob_number,'N'
FROM #observ o
WHERE  o.start_time > '$sms_start' and o.start_time < '$first_acq_time'
  and o.type != 'CAL'
EOQ
      
      $count = DoDBI( $db, $query);
      PrintMsg("I", "$count jitter datasets mapped to SMS start event.");

    }
#---------------------------------------------------------------------
# if there are any acquisitions, map datasets to gs acquisitions 
# and insert gsa_data record for each acquisition that occurs after
# the SMS start time (skipping acquisition found for replans).
#---------------------------------------------------------------------
    $accum = 0;
    $acq_count = 0;
    if ($first_acq_time lt $sms_stop) {

#---------------------------------------------------------------------
#  Query first #acq_times
#---------------------------------------------------------------------

$query = <<"EOQ";
SELECT event_time, gsa_rootname
FROM #acq_times
WHERE event_class='BOA' and event_name != 'GSACQ2'
EOQ
      $sth = DoDBIexecute( $db2, $query);
      ($next_evt_time, $gsa_rootname) = DoDBIfetch( $db2, $query, $sth);
      if (!defined($next_evt_time)) {$next_evt_time = $sms_stop;}

      while ($next_evt_time lt $sms_stop) {
        if ($next_evt_time eq $last_acq_time) {
          $next_acq_time = $sms_stop;
          $next_rootname = " ";
        } else {
#---------------------------------------------------------------------
#  Query next #acq_times
#---------------------------------------------------------------------
          ($next_acq_time,$next_rootname) = DoDBIfetch( $db2, $query, $sth);
          if (!defined($next_acq_time)) {
            $next_acq_time = $sms_stop;
            $next_rootname = " ";
          }
        }
#---------------------------------------------------------------------
# map datasets to GSA event from $next_evt_time to next_acq_time
#---------------------------------------------------------------------
# TRUNCATE, since SQLserver will complain if the data is longer than the field
$jstart = substr($next_evt_time,0,17);

$query = <<"EOQ";
INSERT INTO jitter_evt_map
SELECT '$jstart','GSA',o.program_id,o.obset_id,o.ob_number,'Y'
FROM #observ o
WHERE  o.start_time > '$next_evt_time' and o.start_time < '$next_acq_time'
  and o.type = 'CAL'
UNION
SELECT '$jstart','GSA',o.program_id,o.obset_id,o.ob_number,'N'
FROM #observ o
WHERE  o.start_time > '$next_evt_time' and o.start_time < '$next_acq_time'
  and o.type != 'CAL'
EOQ
        $count = DoDBI( $db, $query);
        $accum+=$count;

#---------------------------------------------------------------------
# insert gsa_data record with default end time of MAX_GSA_DURATION_MIN
# minutes after start, skipping the pre-replan acq that occurs before 
# the sms_start
#---------------------------------------------------------------------
        if ($next_evt_time gt $sms_start) {
          $search_end = AdjustTime($next_evt_time,$MAX_GSA_DURATION_MIN);

          # TRUNCATE since SQLserver will complain if value is longer than field
          $gstart = substr($next_evt_time,0,17);
          $gend   = substr($search_end,0,17);

$query = <<"EOQ";
INSERT INTO gsa_data
VALUES ('$gsa_rootname','$gstart','$gend',' ',' ',' ',0.0,0,0,0) 
EOQ
          DoDBI( $db, $query);
          $acq_count+=1;
	}
        $next_evt_time = $next_acq_time;
        $gsa_rootname  = $next_rootname;

      } # endwhile $next_evt_time...
    } # endif $first_acq_time...
    if (defined($sth)) {
      $sth->finish;  # clears any remaining query rows
    }

    PrintMsg("I", "$acq_count gsa_data records inserted.");
    PrintMsg("I", "$accum jitter_evt_map records inserted for GSA events.");

#---------------------------------------------------------------------
# Insert dataset_link records
#---------------------------------------------------------------------

$query = <<"EOQ";
INSERT INTO dataset_link
SELECT dataset_rootname, dataset_type, program_id, obset_id, ob_number
FROM  #datasets
EOQ
    $count = DoDBI( $db, $query );
    PrintMsg ("I","$count datasets put into dataset_link.");

#---------------------------------------------------------------------
# Insert product_status records for jitter and ast products
#---------------------------------------------------------------------

$query = <<"EOQ";
INSERT INTO product_status
SELECT dataset_rootname, dataset_type, 'N'
FROM  #datasets
EOQ
    $data_count = DoDBI( $db, $query );

#---------------------------------------------------------------------
# Insert product_status records for engineering products
# and use coord_id to screen out STIS MAMA observations
#---------------------------------------------------------------------

$query = <<"EOQ";
INSERT INTO product_status
SELECT dataset_rootname, 'EPC', 'N'
FROM  #datasets d, eng_dataset_pads p
WHERE d.dataset_type = 'FGS' and d.inst = p.inst and p.exp_type='EPC' and
 d.coord_id NOT LIKE 'O[FN]%'  
EOQ
    $data_count += DoDBI( $db, $query );
    PrintMsg ("I",
      "$data_count FGS, EPC and AST records put into product_status.");

#---------------------------------------------------------------------
# Insert product_status records for GSA products
#---------------------------------------------------------------------

$query = <<"EOQ";
INSERT INTO product_status
SELECT gsa_rootname, 'GSA', 'N'
FROM  #acq_times
WHERE event_class='BOA' and event_name!='GSACQ2' and event_time>'$sms_start'
EOQ
    $gsa_count = DoDBI( $db2, $query );
    PrintMsg ("I","$gsa_count GSA records put into product_status.");

#---------------------------------------------------------------------
# Insert product_eng_map records for GSA products
#---------------------------------------------------------------------
    if (($gsa_count + $data_count) > 0) {
      if ($gsa_count > 0) {
         PrintMsg ("I","Computing times for each GSA product.");
$query = <<"EOQ";
SELECT event_time, gsa_rootname
FROM #acq_times
WHERE event_class='BOA' and event_name != 'GSACQ2' and event_time>'$sms_start'
EOQ
        $count=0;
        $sth = DoDBIexecute( $db2, $query);
        while ( ($gsa_time, $gsa_rootname) = DoDBIfetch( $db2, $query, $sth) ) {
          $gsa_start = AdjustTime($gsa_time,-2);
          $gsa_stop  = AdjustTime($gsa_time,$MAX_GSA_DURATION_MIN);
          $count += 
	    (InsertEngMap($db,'GSA',$gsa_rootname,$gsa_start,$gsa_stop));
        }
        if ($count == 0) {
           PrintMsg ("E", "Problem retrieving #acq_times record.");
        }
        else {
           PrintMsg ("I","$count GSA records put into product_eng_map.");
        }
      }
#---------------------------------------------------------------------
# Insert product_eng_map records for dataset products and screen out
# EPC datasets for STIS MAMA using coord_id
#---------------------------------------------------------------------
      if ($data_count > 0) {
         PrintMsg ("I","Computing times for each FGS, EPC and AST product.");

$query = <<"EOQ";
SELECT d.dataset_rootname, d.dataset_type, o.start_time,o.end_time,
       p.start_pad, p.end_pad
FROM #datasets d, #observ o, eng_dataset_pads p
WHERE o.program_id = d.program_id 
  and o.obset_id = d.obset_id 
  and o.ob_number = d.ob_number
  and p.inst = o.inst 
  and p.exp_type = o.type
UNION
SELECT d.dataset_rootname, 'EPC', o.start_time,o.end_time,
       p.start_pad, p.end_pad
FROM #datasets d, #observ o, eng_dataset_pads p
WHERE d.dataset_type = 'FGS' 
  and o.program_id = d.program_id 
  and o.obset_id = d.obset_id 
  and o.ob_number = d.ob_number
  and p.inst = d.inst 
  and p.exp_type = 'EPC'
  and d.coord_id NOT LIKE 'O[FN]%' 
EOQ
        $count=0;
        $sth = DoDBIexecute( $db, $query);
        while ( ($rootname, $data_type, $start_time, $end_time, 
                 $start_pad, $end_pad) = DoDBIfetch( $db, $query, $sth) ) {
 
          $start_time = AdjustTime($start_time,$start_pad);
          $end_time   = AdjustTime($end_time,  $end_pad);
          $recs = InsertEngMap($db2,$data_type,$rootname,$start_time,$end_time);
          $count += $recs;
        }
        if ($count == 0) {
           PrintMsg ("E", "Problem prepping record for product_eng_map.");
        }
#---------------------------------------------------------------------
# Insert product_eng_map records for internal datasets
#---------------------------------------------------------------------

$query = <<"EOQ";
SELECT d.dataset_rootname, d.dataset_type, o.start_time
FROM #datasets d, #observ o
WHERE o.program_id = d.program_id 
  and o.obset_id = d.obset_id 
  and o.ob_number = d.ob_number
  and o.type = 'CAL'
EOQ
        $err_msg = "Cannot get first internal exp for product_eng_map.";
        $err_msg2 = "Cannot get next internal exp for product_eng_map.";

        $sth = DoDBIexecute( $db, $query);
        while ( ($rootname, $data_type, $start_time) = DoDBIfetch( $db, $query, $sth) ) {
          InsertEngMap( $db2,$data_type,$rootname,$start_time,$start_time);
          $count += 1;
        }
        PrintMsg ("I",
	  "$count FGS, EPC and AST records put into product_eng_map.");
      }
    }
#---------------------------------------------------------------------
# Drop temporary tables in db session
#---------------------------------------------------------------------

$query = <<"EOQ";
DROP TABLE #observ
DROP TABLE #datasets
EOQ

    DoDBI( $db, $query);
#---------------------------------------------------------------------
# Drop temporary table in db2 session
#---------------------------------------------------------------------

$query = <<"EOQ";
DROP TABLE #acq_times
EOQ

    DoDBI( $db2, $query);
#---------------------------------------------------------------------
# end of all queries
#---------------------------------------------------------------------
    DoDBIclose($db2);
    DoDBIclose($db);
    PrintMsg ("I","---  end  --- Update Control Tables ----------");
    exit( $PROCESS_SUCCESS);  

#---------------------------------------------------------------------
# end of main procedure -- subroutines follow
#---------------------------------------------------------------------
#---  Insert product_eng_map records using db or db2, returning record count
sub InsertEngMap
{
    my ( $db, $type, $rootname, $next_date, $stop_date) = @_;
    my $query;
    my $count = 0;
    my $next_eng = $next_date;
    $next_eng=~s/^(....)\.(...):(..).+$/T$1$2$3/;
    my $stop_eng = $stop_date;
    $stop_eng=~s/^(....)\.(...):(..).+$/T$1$2$3/;
    while ($next_eng le $stop_eng) {
      $eng_name = $next_eng."00";
$query = <<"EOQ";
INSERT INTO product_eng_map
VALUES ( '$rootname','$type','$eng_name','N')
EOQ

      DoDBI( $db, $query);
      $next_date = AdjustTime($next_date,60);
      $next_eng = $next_date;
      $next_eng=~s/^(....)\.(...):(..).+$/T$1$2$3/;
      $count+=1;
    }
    $count;
}
