#!/usr/bin/perl -w

# Usage: load.newaths.pl <INFIL> <OUTFIL>
#
# Example:  load.newaths.pl newaths.31Dec05.csv newaths.31Dec05.sql
#
# David Harris, Version of 12 Jun 2006 2:00 GMT

$personsernum = 76589;  # SET to beginning value EACH TIME!!!
#  Can run this SQL on the mailing db (emailbase) to get the needed value:
####   SELECT 1+MAX(personsernum) FROM person ;
# ------------------------------------------------

# Check the number of arguments on the command line:
if ($#ARGV+1 != 2) {
  die "load.newaths.pl needs <INFIL> <OUTFIL>  as arguments";
};
# Check existence of the textfile and email listing file:
(open INFIL, "<$ARGV[0]") or die "load.newaths.pl INFIL file $ARGV[0] not found.\n";
(open OUTFIL, ">$ARGV[1]") or die "load.newaths.pl OUTFIL file not made.\n";

## SET $personsernum to beginning value ABOVE, EACH TIME that
##  the output from this is inserted into the mailing database!!!

$personsernum-- ;
#Read through INFIL file:
while ($lineread = <INFIL>) {
  chomp $lineread;
  ($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.
  $email =~ s/<//g;  #Deal with angles around names.
  $email =~ s/>//g;  #Deal with angles around names.
  $email =~ tr/A-Z/a-z/;  #LOWERCASE all letters in emails
  $email =~
    s/^\s*([a-zA-Z0-9_\-]+@[a-zA-Z0-9_\-\.]+)\s*/$1/ ; #Remove WHITESPACE
  
  $personsernum++ ;
  # The format of the SQL INSERT line:
  #print OUTFIL "INSERT INTO `$tablename` (`email`) VALUES (\'$lineread\');\n" ;
  print OUTFIL "INSERT INTO `person` (`personsernum`,`personname`,`email`,`mayemail`,`maydisplay`)
      VALUES (\'$personsernum\',\'$personname\',\'$email\',\'y\',\'n\') ;\n" ;

  print OUTFIL "INSERT INTO `personfacts` (`personsernum`,`factname`,`factvalue1`,`factvalue2`)
  VALUES (\'$personsernum\',\'mthomasaths\',\'Apr2007\',\'NULL');\n"
}
close OUTFIL;
close INFIL;
exit;