#!/usr/local/bin/perl
# Chris Seidel  July 1, 1997
# Program to read a list of Fund names called "MasterList",
# search a comma separated data file: fundname,date,price\n
# reformat the date, then open a file called fundname.dta and 
# append the line to the file.
# 
# usage: updater.pl datafilename
#

$listfile = "/home/pangloss/public_html/Fund/MasterList";

  # get the name of the Data File from the command line
  if( $ARGV[0] =~ /txt$/ ){
    $datafile = $ARGV[0];
  }
  else{
    print "File containing data must end with .txt\n";
    die("Cannot open file $ARGV[0] \n");
  }

  # Open and get the list elements
  unless( open( LISTFILE, $listfile) ){
    die("Cannot open file $listfile \n");
  }
  @list_file = <LISTFILE>;
  close(LISTFILE);


	foreach $element (@list_file){
	   if( $element  =~ /\w/ ){
             chop($element);
             $result = &getData();
             if( $result ){
               @data = split(/,/, $dataline);
               &formatDate($data[1]);
               $dta_line = $date."\t".$data[2];
               &updateFile();
             }
             else{
               print "$element not found\n"
             }
	   }
	}

sub getData {

   $found = 0;

   unless( open(DATAFILE, $datafile) ){
        die("cannot open file $datafile \n");
   }

   while( $dataline = <DATAFILE> ){
      if( $dataline =~ /$element/ ){
        $found = 1;
        last;
      }
   }

   close (DATAFILE);
   return($found);

}

sub formatDate {
    my($line) = @_;
    $date = "";

    $year = substr($line, 0, 2);
    $month = substr($line, 2, 2);
    $day = substr($line, 4, 2);

    $date = $month."/".$day."/".$year;

}

sub updateFile {
	$filename = $data[0].".dta";
	unless( open(DTA_FILE, ">>$filename")){
	    print "Unable to open file: $filename\n";
	    return;
	}
	print DTA_FILE $dta_line;
	close(DTA_FILE);
	print "$filename updated with line:$dta_line";
}