#!/usr/local/bin/perl 

use DBI;

###########################
##   Read in the input   ##
###########################

# make sure input file is defined

# get the arguments and put them in variables

	
if( not defined($ARGV[0]) )
{ 
	die( "No file name supplied\n");
}
else
{
	$file = $ARGV[0];
}

# make sure input file is present

if (!-e $file) 
{
	die( "The file $file doesn't exist." );
}

my $dsn = "DBI:mysql:compound:localhost";	# data source
my $user_name = "chem";						# user name
my $password = "chem";						# password

# connect to database
my $dbh = DBI->connect( $dsn, $user_name, $password,
						{ RaiseError => 1, PrintError => 0 } );

$rows = $dbh->do( qq{ DELETE FROM atom } );
$rows = $dbh->do( qq{ DELETE FROM bond } );
$rows = $dbh->do( qq{ DELETE FROM molecule } );
$rows = $dbh->do( qq{ DELETE FROM name } );

# read the input file into @array

open INPUT_FILE, $file;

while($line=<INPUT_FILE>)
{

	chomp($name=$line);					# read compound name
	$usr_str = <INPUT_FILE>;		# eat user string
	$id_str = <INPUT_FILE>;			# get id info
	@tokens = split(/[ *\,]/,$id_str);	# tokenize id string
	$cas=$tokens[3];
	$count_str = <INPUT_FILE>;
	if( $count_str =~ m!\s+([\d]+)\s+([\d]+)[^\n]*(?=(\n||$))! )
	{
		$atoms = $1;
		$bonds = $2;
	}	
	# insert the molecule data into the molecule table
	
	$rows = $dbh->do( qq{
				INSERT INTO molecule (mol_id, num_atoms, num_bonds, CAS) 
				VALUES( NULL, $atoms, $bonds, 'new' ) } );

	$sth = $dbh->prepare(qq{SELECT mol_id FROM molecule WHERE CAS='new'});
	$sth->execute();

	@ary = $sth->fetchrow_array();
	$mol_id=$ary[0]; 

	$rows = $dbh->do( qq{ UPDATE molecule SET CAS='$cas' WHERE cas='new' });

	$name = $dbh->quote($name);
	$rows = $dbh->do( qq{
					INSERT INTO name (name_id, mol_id, name)
					VALUES( NULL, $mol_id, $name ) } );

	for( $i=1; $i<=$atoms; $i++)
	{
		my $atom_str  = <INPUT_FILE>;
		if( $atom_str =~ m!\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([A-Za-z]+)[^\n]*(?=\n)! )
		{
			my $x = $1;
			my $y = $2;
			my $z = $3;
			my $atom_type = $4;
			$sql= qq{
				INSERT INTO atom (atom_id, mol_id, sequence, x, y, z, atom_type) 
				VALUES( NULL, $mol_id, $i, $x, $y, $z, \'$atom_type\' ) };
			$rows = $dbh->do( $sql );
		}
	}

	for( $i=1; $i<=$bonds; $i++)
	{
		my $bond_str  = <INPUT_FILE>;
		if( $bond_str =~ m!\s+([\d]+)\s+([\d]+)\s+([\d]+)[^\n]*(?=(\n||$))! )
		{
			my $atom_1 = $1;
			my $atom_2 = $2;
			my $bond_type = $3;
			$rows = $dbh->do( qq{
				INSERT INTO bond (bond_id, mol_id, atom_1, atom_2, bond_type) 
				VALUES( NULL, $mol_id, $atom_1, $atom_2, \'$bond_type\' ) } );	
		}
	}
	while($line = <INPUT_FILE>)
	{
		if( $line =~ m/\$\$\$\$/) { last; } #chew up the $$$$
	}
}

close(INPUT_FILE);
$dbh->disconnect();
exit(0);
