#!/usr/bin/perl

$use_mcm_lw_num = 1;


#use strict;
use POSIX;
use DBI;

my $file = shift or die "No filename given.";

open INFILE, "<$file";

if ( $file =~ /chipid_and_results_0x([0-9a-fA-F]*)_w_dmem/ ){
    $wafer = hex $1;
}


# Check header line for correct format
my $l = <INFILE>;

if ($l != "CHIPID_POS CHIPID_BURNED RESULT_WT RESULT_MCMT") {
    print "Invalid format of input file $file\n";
    exit;
}
 

my $dbh = DBI->connect("DBI:Pg:dbname=play",
		       "alice", 'alice!@#',
		       {'RaiseError' => 1});


$sth = $dbh->prepare("INSERT ".
		     "INTO wafer_test(wafer,trapid,laserid,status,mcmexpect) ".
		     "VALUES (?,?,?,?,?)");

$ntraps = 0;

while ($l = <INFILE>) {
    
    #die "Read failed from file $file, line $l"
    #unless (

    chop $l;

    $l =~ /^(\d*) ([0-9\-]*) (\d*) (\d*)$/;
    $trap      = $1;
    $laserid   = $2;
    $status    = $3;
    $mcmexpect = $4;
 
#    ($trap, $laserid, $status, $mcmexpect) = split(' ', $l);
   
    if ( ! $trap ) {
	print "Read failed from file $file\n  line ..$l..\n";
	next;
    }

    undef($laserid) if ($laserid eq '');

    $ntraps++;

    
    #   print "$trap --- $laserid --- $status --- $mcmexpect\n";

    $sth->execute($wafer, $trap, $laserid, $status, $mcmexpect);
    
	
}

print "$ntraps TRAPs read from $file\n";

$dbh->disconnect;

