#!/usr/bin/perl 

#load_primers	-Load primer info into the primers table.
#
#---------------------------
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#---------------------------
#
#Version: 0.001
#
#Last modified: 8-05
#Written by Jim Lund, Department of Biology, University of Kentucky
#jiml at uky dot edu
#
#Web site: http://elegans.uky.edu
#---------------------------
#HISTORY:
#v.001	8-3-05
#Initial version.
#

use DBI;
use WebConfig;


#
#Subroutines
#


BEGIN {
  WebConfig::CGI_init;
}


#
#Initailize db connection.
#
my ($dbh,$DB_DATE) = WebConfig::DB_init;


my $primers_file = $ARGV[0];


#
#Load gene->key mappings for name_type 'sjj_primer'.
#
my $name_type;
my $name_types = WebConfig::Name_types;
foreach $descr (keys %$name_types) {
  if ($descr =~/sjj/i) {
    $name_type = $$name_types{$descr}{'name_type'};
	last;
  }
}

my $id_to_name = WebConfig::Map_all_ids;



#
#Fill primers table.
#
open(PRI,$primers_file) || die "Can't open primers file $primers_file: $!\n";

my $skip = <PRI>;


my $sth = $dbh->prepare("INSERT INTO sjj_primers VALUES (?,?,?,?,?,?,?,?,$DB_DATE)");


my $counter = 0;
while (<PRI>) {
  my ($gene,$primer_l,$primer_r,$plate,$l_tm,$r_tm,$product_len,$bp_coding,$qual,$cDNA_len) = split(/\t/);
  $gene = uc($gene);

#
#Get the gene_name_key for this gene from table 'gene'.  If it doesn't exist, add the gene to
#tables 'gene' and to 'name_to_gene'.
#
  my $key;
  if (defined $$id_to_name{$gene}{$name_type}) {

	$key = WebConfig::Get_gene_key($gene);

  }else{

	$key = WebConfig::Get_gene_key($gene);

    if (!$key) { $key = WebConfig::Add_gene([ $gene ]); }

	$dbh->do("INSERT INTO name_to_gene VALUES ($key, $name_type, '$gene', NULL, $DB_DATE)");

  }


#
#Now add to table 'sjj_primers'.
#
  $sth->execute($key, $primer_l, $l_tm, $primer_r, $r_tm, $product_len, $bp_coding, $qual);

  $counter++;
  if (!($counter % 500)) { print STDERR "Added $counter primers.\n"; }
}

close PRI || warn "Can't close primer file $primers_file: $!\n";

print STDERR "Added $counter primers.\n";


exit;


