##########################################################################
#
# routine: db_dark_association.pl
#
# Purpose: Look up a dataset name in the nic_saa_link relation.
#          Return the corresponding saa-dark ASN name, if found.
#
# Input:   $DSET - name of exposure to look up
#          ENV.DSQUERY - name of DB server
#          ENV.OPUS_DB - name of database containing nic_saa_link
#
# Output:  $SAA_DARK_ASN - name of the corresponding SAA-dark ASN (if found)
#
# Return:  name of SAA-dark ASN if found
#          "" if no dark ASN found or an error occurred
#
# Calls:   PrintMsg
#
# modification history:
#
#   date    opr     who     reason
# -------- -----  --------  --------------------------------------
# 09/03/00 43165  MSwam     first version
# 03/25/10 64274    MSwam     Replace ST_DBlib with DBI
# 06/30/10 64432    MSwam     Use single quotes for SQLServer
# 
#########################################################################
sub DB_dark_association{
    my ($DSET) = @_;                            # ARGUMENTS from @_
    my ($db, $progid, $obset, $obnum, $query, $count);  # LOCAL VARS
    my ($dark_association);

    # intialize as if failed
    $dark_association = "";

    require 'do_dbi_pkg.pl';

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

    my $db = STScI::DBI->connect( "dbi:Sybase:server=$server");

    if (!defined($db)) {
        PrintMsg("E","Cannot connect to server: $DBI::errstr");
        return;
    }
    DoDBI($db,"use $database"); # open database

    # split the dataset name into its components
    $progid = substr($DSET,1,3);
    $obset  = substr($DSET,4,2);
    $obnum  = substr($DSET,6,2);

    $query = <<"EOQ";
SELECT dark_association FROM nic_saa_link
WHERE program_id = '$progid' and obset_id = '$obset' and
      ob_number = '$obnum'
EOQ
    $count = 0;
    $sth = DoDBIexecute( $db, $query);
    while ( ( $tmp ) = DoDBIfetch( $db, $query, $sth) ) {
        $dark_association = $tmp;
        PrintMsg("I","found $dark_association in nic_saa_link for $progid$obset$obnum");
        $count++;
    }
    PrintMsg("I","$DSET: nic_saa_link count = $count");

    DoDBIclose($db);
    $dark_association;   # return value
}
1;
