#!/usr/bin/perl -w

# Usage: load.prs.pl <INFIL> <OUTFIL> <starting-serial-number>
#
# Example:  load.prs.pl prs.31Dec05.csv prs.31Dec05.sql dummy
#
# David Harris, Version of 1 Jan 2006 21:06 PST

# ------------------------------------------------

# Check the number of arguments on the command line:
if ($#ARGV+1 != 3) {
  die "load.prs.pl needs <INFIL> <OUTFIL> <starting-serial-number> as arguments";
};
# Check existence of the textfile and email listing file:
(open INFIL, "<$ARGV[0]") or die "load.prs.pl INFIL file $ARGV[0] not found.\n";
(open OUTFIL, ">$ARGV[1]") or die "load.prs.pl OUTFIL file not made.\n";
$startsernums = $ARGV[2];
chomp $startsernums;
$lastemail = '';
$personsernum = $startsernums;  # SET to beginning value by 3rd argument, EACH TIME!!!
$personsernum-- ;
#Read through INFIL file:
while ($lineread = <INFIL>) {
  chomp $lineread;
  ($papername,$stateprovetc,$personname,$email) = split(/\|/, $lineread);
  $personname =~ s/'/\\'/g;  #Deal with O'Connor etc.
  $personname =~ s/"//g;  #Deal with quotes around names.
  $email =~ s/'/\\'/g;  #Deal with O'Connor etc.
  $email =~ s/"//g;  #Deal with quotes around names.

  if ($lastemail ne $email) {  #Skip duplicated emails!  Assumes email sorted list
    $personsernum++ ;
    # The format of the SQL INSERT line:
    #print OUTFIL "INSERT INTO `$tablename` (`email`) VALUES (\'$lineread\');\n" ;
    print OUTFIL "INSERT INTO `PERSON`
          (\`personsernum\`,\`personname\`,
          \`stateprovetc\`,\`country\`, \`email\`)
        VALUES ($personsernum,\'$personname\',
          \'$stateprovetc\',892,\'$email\');\n" ;

    print OUTFIL "INSERT INTO `PERSONFACTS` (`personsernum`,`factname`,`factvalue1`,`factvalue2`)
      VALUES ($personsernum,\'withpaper\',\'$papername\',\'NULL');\n" ;    
  }
  if ($lastemail eq $email) {
    #$personsernum-- ;
    print OUTFIL "INSERT INTO `PERSONFACTS` (`personsernum`,`factname`,`factvalue1`,`factvalue2`)
      VALUES ($personsernum,\'withpaper\',\'$papername\',\'NULL');\n" ;       
  }
  $lastemail = $email;
}
close OUTFIL;
close INFIL;
exit;