#!/usr/bin/perl -w
###
# selectFolder - script to select a subset of records based on Folder name.
#
# This script also produces output records in the correct format for 
# using with my TeX file.
#
# Christopher Rath
# crath@cyberus.ca
###

use CSV;		# Comma Separated Value module.

###
# Constants for reading Newton Names records.
#
my($LAST_NM) = "Last Name";
my($FIRST_NM) = "First Name";
my($MIDDLE_NM) = "Middle Name";
my($MR_MS) = "Ms./Mr.";
my($TITLE) = "Title";
my($COMPANY) = "Company";
my($AD1_ST_1) = "Address 1 - Street (Line 1)";
my($AD1_ST_2) = "Address 1 - Street (Line 2)";
my($AD1_CITY) = "Address 1 - City";
my($AD1_STATE) = "Address 1 - State";
my($AD1_ZIP) = "Address 1 - Zip Code";
my($AD1_COUNTRY) = "Address 1 - Country";
my($AD2_ST_1) = "Address 2 - Street (Line 1)";
my($AD2_ST_2) = "Address 2 - Street (Line 2)";
my($AD2_CITY) = "Address 2 - City";
my($AD2_STATE) = "Address 2 - State";
my($AD2_ZIP) = "Address 2 - Zip Code";
my($AD2_COUNTRY) = "Address 2 - Country";
my($FOLDER) = "Folder";


###
# Get filename to process.
#	* for now we'll cop-out and hard-code a name.
#
($#ARGV != 1) || die "$0 : USAGE: $0 <NewtonDataFile>\n"; 

my($input)      = $ARGV[0]; 

### 
# Open the input file for processing. 
# 
if (!open(INPUT, "$input")) { 
    die "$0: ERROR, cannot open input file, $input\n" 
      ."\tno data generated.\n"; 
} else { 
    my($firstLine) = scalar(<INPUT>); 
    my(%CSVfields) = CSVinit($firstLine); 

    # 
    # Validate field list to ensure data file contains all the fields we need. 
    # 

    if (! CSVvalidate(\%CSVfields, $LAST_NM, $FIRST_NM, $MIDDLE_NM, $MR_MS, $TITLE,
		      $COMPANY, $AD1_ST_1, $AD1_ST_2, $AD1_CITY, $AD1_STATE, $AD1_ZIP,
		      $AD1_COUNTRY, $AD2_ST_1, $AD2_ST_2, $AD2_CITY, $AD2_STATE,
		      $AD2_ZIP, $AD2_COUNTRY, $FOLDER)) {

	die "Some fields are missing from the input file."; 
    } else {
	my($first) = 1;			# Only true for first record output.
	my(@record);                    # Where we'll store parsed records.
	my($outrec,			# Output record (a string).
	   $wk_ad1,			# Address working string.
	   $wk_ad2);			# Address working string.

	#### 
	# Process input file, summarizing results. 
	# 
	while (<INPUT>) { 
	    @record = CSVsplit($_);

	    print "$record[$CSVfields{$FOLDER}]\n";
	}
    }
}
