#!/usr/bin/perl -w

# Usage: load.arthurs2005.pl <INFIL> <OUTFIL> <starting-serial-number>
#
# Example:  load.arthurs2005.pl arthurs2005.txt arthurs2005.sql 4480
#
# David Harris, Version of 1 Jan 2006 23:06 PST

# ------------------------------------------------

# Check the number of arguments on the command line:
if ($#ARGV+1 != 3) {
  die "load.arthurs2005.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.arthurs2005.pl INFIL file $ARGV[0] not found.\n";
(open OUTFIL, ">$ARGV[1]") or die "load.arthurs2005.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;
  ($grptype,$email,$grpname) = split(/\|/, $lineread);
  $grpname =~ s/'/\\'/g;  #Deal with O'Connor etc.
  $grpname =~ 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\`,\`email\`,\`country\`)
        VALUES ($personsernum,\'$email\',   892);\n" ;

    print OUTFIL "INSERT INTO `PERSONFACTS` (`personsernum`,`factname`,`factvalue1`,`factvalue2`)
      VALUES ($personsernum,\'isarthurslist\',\'$grptype\',\'$grpname');\n" ;    
  }
  if ($lastemail eq $email) {
    #$personsernum-- ;
    print OUTFIL "INSERT INTO `PERSONFACTS` (`personsernum`,`factname`,`factvalue1`,`factvalue2`)
      VALUES ($personsernum,\'isarthurslist\',\'$grptype\',\'$grpname');\n" ;    
  }
  $lastemail = $email;
}
close OUTFIL;
close INFIL;
exit;