use strict;
#use warnings; #Warnings are off so that variables don't need to be undefined across scripts.

#At the top we download the files

open (FTP, ">ftpcommands.txt"); #Create a text file of the ftp commands for the windows builtin ftp client
print FTP "hash\nget /pub/kegg/ligand/reaction/reaction reaction\nget /pub/kegg/ligand/glycan/glycan glycan\nget /pub/kegg/ligand/compound/compound compound\nquit";
close FTP;

system "ftp -A -s:\"ftpcommands.txt\" ftp.genome.jp";

#This script is the combination of many smaller scripts that I used to run sepearetely.
#They should all work together in this script, meaning I have only one *.exe file to run once the script is compiled using perl2exe
#The only additions are ensuring that filehandles are closed after each script runs
#perl mrp.pl & perl mrn.pl & perl parseKEGGreactionfile.pl & perl createRPandRRtables.pl & perl ECReactionLink.pl & perl newmcn.pl & perl glycanparser.pl"

#mrp.pl
open (REACTION, "reaction");
open (MRP, ">multiplereactionpathways.txt");
open (PRP, ">preferredreactionpathway.txt");

my $CompoundID;
my $pathwayflag = 1; # A flag to check if an entry is finished without a name being found
my $pathway ="";
my @pathways;
my $preferredpathway;

#Headers
print MRP "Reaction ID\tKegg Pathway\n"; #Print each name
print PRP "Reaction ID\tKegg Pathway\n"; #Print preferred name

while (<REACTION>)
	{
	my $line = $_;
	chomp $line;
	if ($line =~ m/ENTRY/ and $line =~ m/\s\s([R]\d\d\d\d\d)/ and $line !~ m/Same/ and $line !~m/Obsolete/ and $line !~m/Transferred/)
		{
		$CompoundID = $1;
		$pathwayflag = 1;
		}
	
	if ($line =~ m/rn\d{5}\s\s(.{2,})/)
		{
		#print "$1\n";
		$pathway .= "$1\@";
		@pathways = split(/@/, $pathway);
		$pathwayflag = 0;
		}
		
	if ($line =~ m/\/\/\// and $pathwayflag == 0)
		{
		foreach my $alternativepathway (@pathways) 
		{
		if (! (defined ($preferredpathway)))
			{
			$preferredpathway = $alternativepathway;
			}
		print MRP "$CompoundID\t$alternativepathway\n"; #Print each name
		}
		print PRP "$CompoundID\t$preferredpathway\n"; #Print preferred name
		undef $preferredpathway;
		$pathway = "";
		}
		
	if ($line =~ m/\/\/\// and $pathwayflag == 1)
		{
		print MRP "$CompoundID\tNO KEGG PATHWAY\n"; #Print each name
		print PRP "$CompoundID\tNO KEGG PATHWAY\n"; #Print preferred name
		$pathway = "";
		}
	#print "line = $line \t nonameflag = $nonameflag \n";
	}


print "Creating reaction-pathway link list...";
print "Done.\n";
print "Creating reaction list...";

close REACTION;
close MRP;
close PRP;

#mrn.pl
open (REACTION, "reaction");
open (MRN, ">multiplereactionnames.txt");
open (PRN, ">preferredreactionname.txt");

#Headers
print MRN "Reaction ID\tName\tSource\n";
print PRN "Reaction ID\t Preferred Name\tSource\n";

my $CompoundID;
my $nonameflag = 1; # A flag to check if an entry is finished without a name being found
my $pathway ="";
my @names;
my $preferredname;

while (<REACTION>)
	{
	my $line = $_;
	chomp $line;
	if ($line =~ m/ENTRY/ and $line =~ m/\s\s([R]\d\d\d\d\d)/ and $line !~ m/Same/ and $line !~m/Obsolete/ and $line !~m/Transferred/)
		{
		$CompoundID = $1;
		$nonameflag = 1;
		}
	if ($line =~ m/NAME/ and $line !~ m/Transferred/)
		{
		$nonameflag = 0;
		my $nameline = $line;
		my $nextline = <REACTION>;
		chomp $nextline;
		while ($nextline !~ m/[A-Z][A-Z][A-Z][A-Z]/)
			{
			$nameline .= $nextline;
			$nextline = <REACTION>;
			chomp $nextline;
			}
		my $names = substr ($nameline, 12);
		while($names =~ m/\s{2}/)
			{ 
			$names =~ s/;\s{12}/@/;#Change semicolons to @ if followed by 12 spaces (@ is a safe character for line splitting later)
			$names =~ s/\s{2,}//;#Removes all but single spaces
						} 
		@names = split(/@/, $names); #Split each name
		}
		
	if ($line =~ m/\/\/\// and $nonameflag == 0)
		{
		foreach my $alternativename (@names) 
		{
		if ((! (defined ($preferredname))) or (length($preferredname) > length($alternativename) + 10))
			{
			$preferredname = $alternativename;
			}
		print MRN "$CompoundID\t$alternativename\tKEGG\n"; #Print each name
		}
		print PRN "$CompoundID\t$preferredname\tKEGG\n"; #Print preferred name
		undef $preferredname;
		$pathway = "";
		}
		
	if ($line =~ m/\/\/\// and $nonameflag == 1)
		{
		print MRN "$CompoundID\tNO NAME\tKEGG\n";
		print PRN "$CompoundID\tNO NAME\tKEGG\n";
		$pathway = "";
		$nonameflag = 0;
			
		}
	#print "line = $line \t nonameflag = $nonameflag \n";
	}

print "Done.\n";

close REACTION;
close MRN;
close PRN;

#parseKEGGreactionfile.pl
print "Parsing the KEGG reaction file...";

my %reactionname;
my %reactiondefinition;
my %reactionequation;
my %reactionpathway;

parsereactionfile();

sub parsereactionfile
#(all the lines should be considered as possibly more than one line incase of redundant naming, equation or definition line runover etc,,, and dealt with appropriately)
	{
	open (PARSED, ">parseKEGGreactionfileOUT.txt");
	print PARSED "Reaction Number\tName\tDefinition\tEqaution\tPathway\n";
	open (REACTIONFILE, "reaction");
	my $recordcounter = 0;
	my $fifthline;
	
	while (<REACTIONFILE>)
		{
		my $firstline = $_;
		chomp $firstline;
		while ($firstline !~ "ENTRY")
			{
		#	print "First line does not contain ENTRY, I'm reading ahead\n";
			$firstline = <REACTIONFILE>;
			chomp $firstline;
			}
		#	print "firstline = $firstline";
		my @firstline = split (" ", $firstline);
		my $rnumber = $firstline[1];
		
		my $secondline = <REACTIONFILE>;
		chomp $secondline;
		#print "secondline = $secondline";
		my @secondline = split ("        ", $secondline);
		my $thirdline;
		if ($secondline[0] !~ "NAME")
			{
		#	print "Second line does not contain NAME as expected, maybe this reaction doesn't have a NAME\n";
			$thirdline = $secondline;
			$reactionname{$rnumber} = "NO NAME";
			}
		else
			{
			$reactionname{$rnumber} = $secondline[1];
			$thirdline = <REACTIONFILE>;
			chomp $thirdline;
			}
		
		while ($thirdline !~ "DEFINITION")
			{
		#	print "Appending Third line to NAME\n";
			my @thirdline = split ("            ", $thirdline);
		#	print "thirdline = $thirdline[1]\n";
			my $newname = "$secondline[1] $thirdline[1]";
			$reactionname{$rnumber} = $newname;
			$thirdline = <REACTIONFILE>;
			chomp $thirdline;
			}
		my @thirdline = split ("  ", $thirdline);
		#print "thirdline = $thirdline";
		$reactiondefinition{$rnumber} = $thirdline[1];
			
		my $fourthline = <REACTIONFILE>;
		chomp $fourthline;
		
		while ($fourthline !~ /EQUATION/)
			{
		#	print "Appending Fourth line to DEFINITION\n";
			my @fourthline = split(/            /, $fourthline);
			my $newdefinition = "$reactiondefinition{$rnumber} $fourthline[1]";
			$reactiondefinition{$rnumber} = $newdefinition;
			$fourthline = <REACTIONFILE>;
			chomp $fourthline;
			}
		
		my @fourthline = split ("    ", $fourthline);
		$reactionequation{$rnumber} = $fourthline[1];
		my $fourthandahalfline = <REACTIONFILE>;
		chomp $fourthandahalfline;
		
		while ($fourthandahalfline !~  /(RPAIR|COMMENT|ENZYME|PATHWAY|REMARK|\/\/\/)/)
			{
			#print "appended equation line at $fourthandahalfline\n";
			my @fourthandahalfline = split ("            " , $fourthandahalfline);
			my $neweq = "$fourthline[1] $fourthandahalfline[1]";
			$reactionequation{$rnumber} = $neweq;
			$fourthandahalfline = <REACTIONFILE>;
			chomp $fourthandahalfline;
			}
		#print "fourthline = $fourthline";
		
		#my $fifthline; moved up to top
		
		#now search until the //// end of section marker for pathway information (if any)
		if ($fourthandahalfline =~ m/(PATHWAY|\/\/\/)/)
			{
			$fifthline = $fourthandahalfline;
			}
		else
			{
			$fifthline = <REACTIONFILE>;
			chomp $fifthline;
			}

			
		while ($fifthline !~ "///") #add a case for if fifthline is empty
			{
			if ($fifthline =~ /PATHWAY/) 
				{
				my @fifthline = split ("     ", $fifthline);
				$reactionpathway{$rnumber} = $fifthline[1];
				}
			$fifthline = <REACTIONFILE>;	
			chomp $fifthline;
			}
		
#			$recordcounter++;
			#print "record $recordcounter\n";

		}
		
for (sort keys %reactionname)
		{
		# fixes the non seperated + problem
		while($reactiondefinition{$_} =~ m/[a-z]([a-z])\+/g)
			{
			my $mistake = $1;
			print "non seperated + problem found at $reactiondefinition{$_}\n";
			$reactiondefinition{$_} =~ s/$mistake\+/$mistake \+/;
			print "non seperated + problem resolved to $reactiondefinition{$_}\n";
			}
		if (exists $reactionpathway{$_})
			{
			print PARSED "$_\t$reactionname{$_}\t$reactiondefinition{$_}\t$reactionequation{$_}\t$reactionpathway{$_}\n";
			}
		else
			{
			print PARSED "$_\t$reactionname{$_}\t$reactiondefinition{$_}\t$reactionequation{$_}\t\n";
			}
		}
		
	close (PARSED);
	close (REACTIONFILE);
	}
	
print " Done.\n";
print "Creating Reaction-Product and Reaction-Reaction Linking Tables...";

#createRPandRRtables.pl

# This program also creates the G compound list which is a list of compounds for which the Compound ID starts with a G and is thus not contained within the KEGG Compound file

open (APPENDED, "parseKEGGreactionfileOUT.txt"); 
open (REACTANTS, ">reactants.txt");
open (PRODUCTS, ">products.txt");
#open (GCOMPOUNDS, ">GCompounds.txt");
#open (INVERTEDGCOMPOUNDS, ">invertedGCompounds.txt");

#Headers
print REACTANTS "Reaction ID\tCompound ID\tStoichiometry\n";
print PRODUCTS "Reaction ID\tCompound ID\tStoichiometry\n";

my (@rnumbers, %species, %SBMLreaction);
	parsereactionsfile();
my $length = scalar @rnumbers;
#print "There are $length reactions in the loaded file...\n";

close (APPENDED);
close (REACTANTS);
close (PRODUCTS);

# This subroutine has got too big and complicated, I need to write a better one that's smaller.
sub parsereactionsfile
	{
	my %reactionstosbml;
	my $counter = 0;
	my %Gcompounds;
	my %invertedGcompounds;
	
	while (<APPENDED>)
		{
		if ($_ =~ "R0")
			{
			$_ =~ s/^\s+//; #trims leading whitespace
			$_ =~ s/\s+$//; #trims trailing whiespace
			my @line = split ("\t", $_);

		if (scalar @line < 2)
			{
			print "Reactions ignored: there are no reactions details for $_ \n";
			next;
			}
			
		if (exists $reactionstosbml{$line[0]})
			{
			print "Duplicate reaction, reaction $line[0] ignored this time\n";
			next;
			}
			
			my $rnumber = $line[0];
			my $rname = $line[1];
			my $specialreaction = $line[6];
			$reactionstosbml{$rnumber}=$rname; #part of dirty hack to remove duplicate entries
			$rnumbers[$counter]=$rnumber;

			my @splitlinedef = split (/ <=>/, $line[2]);
			for(@splitlinedef)
				{
				$_ =~ s/^\s+//; #trims leading whitespace
				$_ =~ s/\s+$//; #trims trailing whiespace
				}
			my @reactantsdef = split (/ \+/, $splitlinedef[0]);
				for(@reactantsdef)
				{
				$_ =~ s/^\s+//; #trims leading whitespace
				$_ =~ s/\s+$//; #trims trailing whiespace			
				}
			my @productsdef = split (/ \+/, $splitlinedef[1]);
				for(@productsdef)
				{
				$_ =~ s/^\s+//; #trims leading whitespace
				$_ =~ s/\s+$//; #trims trailing whiespace
				}
				
			my @splitlineeq = split (/ <=> /, $line[3]);
				for(@splitlineeq)
				{
				$_ =~ s/^\s+//; #trims leading whitespace
				$_ =~ s/\s+$//; #trims trailing whiespace
				}
			my @reactantseq = split (/ \+ /, $splitlineeq[0]);
				for(@reactantseq)
				{
				$_ =~ s/^\s+//; #trims leading whitespace
				$_ =~ s/\s+$//; #trims trailing whiespace
				}
			
			my @productseq = split (/ \+ /, $splitlineeq[1]);
				for(@productseq)
				{
				$_ =~ s/^\s+//; #trims leading whitespace
				$_ =~ s/\s+$//; #trims trailing whiespace
				}
			
	my %stoichreact;
			
			for (@reactantseq)
				{
				if ($_ =~ /\d /)
					{
					if ($_ =~ /(\D|-)\d /) #gets rid of the n-1 and CO2 problem
						{
						next;
						}
					my @streacts = split (/\s/, $_);
					$_ = $streacts[1];
					$stoichreact{$streacts[1]} = $streacts[0];
					}
				else
					{
					$stoichreact{$_} = 1;
					}
				}
		
	my %stoichprod;
	
			for (@productseq)
				{
				if ($_ =~ /\d /)
					{
					if ($_ =~ /(\D|-)\d /) #skips something weird
						{
						next;
						}
					my @stprods = split (/\s/, $_);
					$_ = $stprods[1];
					$stoichprod{$stprods[1]} = $stprods[0];
					}
				else
					{
					$stoichprod{$_} = 1;
					}
				}
			
			# Reactants
			my $reactcounter = 0;		
			for(@reactantseq)
				{
				if ($_ =~ m/(G\d\d\d\d\d)/)
					{
					$Gcompounds{$1} = $reactantsdef[$reactcounter]." (G alternate)";
					$invertedGcompounds{$reactantsdef[$reactcounter]." (G alternate)"} = $1;
					}
				$_ =~ m/(\w\d\d\d\d\d)/; #gets rid of prefixes and suffixes
				print REACTANTS "$rnumber\t$1\t$stoichreact{$_}\n";
				
				$reactcounter++;
				}
			
			my $productcounter = 0;
			for(@productseq)
				{
				if ($_ =~ m/(G\d\d\d\d\d)/)
					{
					$Gcompounds{$1} = $productsdef[$productcounter]." (G alternate)";
					$invertedGcompounds{$productsdef[$productcounter]." (G alternate)"} = $1;
					}
				$_ =~ m/(\w\d\d\d\d\d)/; #gets rid of prefixes and suffixes
				print PRODUCTS "$rnumber\t$1\t$stoichprod{$_}\n";
				
				$productcounter++;
				}
							
			my $size = scalar @reactantsdef;
				for (my $n=0; $n<$size; $n++)
					{
					$species{$reactantseq[$n]}=$reactantsdef[$n];
					}
			
			my $size2 = scalar @productsdef;
				for (my $i=0; $i<$size2; $i++)
					{
					$species{$productseq[$i]}=$productsdef[$i];
					}
					
			$counter++;				
			}	
		}
	
	# print "Compounds beginning with a G that need researching\n";
	# foreach (sort keys %Gcompounds)
		# {
		# print GCOMPOUNDS "$_\t$Gcompounds{$_}\n";
		# }
	# foreach (sort keys %invertedGcompounds)
		# {
		# print INVERTEDGCOMPOUNDS "$_\t$invertedGcompounds{$_}\n";
		# }
		
	}

print " Done.\n";	
print "Creating EC Number - Reaction ID Linking Table...";

#ECReactionLink.pl

open (REACTION, "reaction");
open (MECN, ">multipleECnumbers.txt");
open (PECN, ">preferredECnumber.txt");

my $CompoundID;
my $nonameflag = 1; # A flag to check if an entry is finished without a name being found

#Headers

print MECN "Reaction ID\tEC number\n";
print PECN "Reaction ID\tEC number\n";

while (<REACTION>)
	{
	my $line = $_;
	chomp $line;
	if ($line =~ m/ENTRY       ([R]\d\d\d\d\d)/ and $line !~ m/Same/ and $line !~m/Obsolete/ and $line !~m/Transferred/)
		{
		$CompoundID = $1;
		}
	if ($line =~ m/ENZYME/ and $line !~ m/Transferred/)
		{
		$nonameflag = 0;
		my $nameline = $line;
		my $nextline = <REACTION>;
		chomp $nextline;
		while ($nextline !~ m/[A-Z][A-Z][A-Z][A-Z]/ and $nextline !~ m/\/\/\//)
			{
			$nameline .= $nextline;
			$nextline = <REACTION>;
			#print $nextline;
			chomp $nextline;
			}
		my $names = substr ($nameline, 12);
		#while($names =~ m/\s{2}/)
		#	{ #Removes all but single spaces
		#	$names =~ s/\s{2,}//;
		#	} 
		my @names = split(/\s{2,}/, $names); #Split each name
		
		my $preferredname;
		
		my $existingdashcount = 4;
		foreach my $alternativename (@names) 
		{
		my $newdashcount = ($alternativename =~ tr/-//); #Counts the number of dashes
		
		if ((! (defined ($preferredname))) or $newdashcount < $existingdashcount)
			{
			$preferredname = $alternativename;
			$existingdashcount = ($preferredname =~ tr/-//);
			#print "$newdashcount";
			}
		print  MECN "$CompoundID\t$alternativename\n"; #Print each name
		}
		print  PECN "$CompoundID\t$preferredname\n"; #Print preferred name
		}
	if ($line =~ m/\/\/\// and $nonameflag == 1)
		{
		#print "$CompoundID has no name on line $line\n";
		}
	#print "line = $line \t nonameflag = $nonameflag \n";
	}

print " Done.\n";
print "Adding standard compounds to the list of compounds...";

close REACTION;
close MECN;
close PECN;

#newmcn.pl

open (COMPOUND, "compound");
open (MCN, ">multiplecompoundnames.txt");
open (PCN, ">preferredcompoundname.txt");

#Headers
print MCN "Compound ID\tCompound Name\n";
print PCN "CompoundID\tCompound Name\tFormula\n";

my $CompoundID;
my $nonameflag; # A flag to check if an entry is finished without a name being found
my $noformulaflag;
my $formula; 
my @formulaline;

while (<COMPOUND>)
	{
	my $line = $_;
	chomp $line;
	if ($line =~ m/\s\s([C|G|D]\d\d\d\d\d)/ and $line !~ m/Same/ and $line !~m/Obsolete/ and $line !~m/Transferred/)
		{
			$CompoundID = $1;
			$nonameflag = 1;
		}
	if ($line =~ m/NAME/ and $line !~ m/Transferred/)
		{
			$nonameflag = 0;
			my $nameline = $line;
			my $nextline = <COMPOUND>;
			chomp $nextline;
			while ($nextline !~ m/FORMULA/ and $nextline !~ m/\/\/\// and $nextline !~ m/[A-Z]{4,}\s/)
				{
				$nameline .= $nextline;
				$nextline = <COMPOUND>;
				chomp $nextline;
				#Updated section for formula parsing
				if ($nextline =~ m/FORMULA/)
					{
					@formulaline = split(/     /, $nextline);
					$formula = $formulaline[1];
					}
				#End of updated section
				}
			if ($nextline =~ m/FORMULA/) #which it should unless there's no formula
				{
				@formulaline = split(/     /, $nextline);
				$formula = $formulaline[1];
				}

			my $names = substr ($nameline, 12);
			while($names =~ m/\s{2}/)
				{ #Removes all but single spaces
				$names =~ s/\s{2,}//;
				} 
			my @names = split(/;/, $names); #Split each name
			#print "@names\n";
			#Additional section to parse the FORMULA
				
			foreach my $alternativename (@names) 
			{
			if ((! (defined ($preferredname))) or (length($preferredname) > length($alternativename) + 10))
				{
				$preferredname = $alternativename;
				}
			print MCN "$CompoundID\t$alternativename\n"; #Print each name
			}
		print PCN "$CompoundID\t$preferredname\t$formula\n"; #Print preferred name
		$nextline=();
		}

		if ($line =~ m/\/\/\// and $nonameflag == 1) #If we get to the end of the entry without a name
			{
			print "$CompoundID has no name on line $line\n";
			print MCN "$CompoundID\tGlycan $CompoundID\n";
			print PCN "$CompoundID\tGlycan $CompoundID\t$formula\n";
			}
	
	$formula=();
	$preferredname=();
	}

print " Done.\n";
print "Adding Glycans to the list of compounds...";

close COMPOUND;
close MCN;
close PCN;

#glycanparser.pl

open (COMPOUND, "glycan");
#open (MGN, ">multipleglycannames.txt"); #create own list
#open (PGN, ">preferredglycanname.txt");

open (MGN, ">>multiplecompoundnames.txt"); #append to compounds list
open (PGN, ">>preferredcompoundname.txt");

my $CompoundID;
my $nonameflag = 1; # A flag to check if an entry is finished without a name being found

while (<COMPOUND>)
	{
	my $line = $_;
	chomp $line;
	if ($line =~ m/ENTRY/ and $line =~ m/\s\s([G]\d\d\d\d\d)/ and $line !~ m/Same/ and $line !~m/Obsolete/ and $line !~m/Transferred/)
		{
		$CompoundID = $1;
		$nonameflag = 1;
		}
	#in case there isn't a name call it glycan
	if ($line =~ m/NAME/ and $line !~ m/Transferred/)
		{
		$nonameflag = 0;
		my $nameline = $line;
		my $nextline = <COMPOUND>;
		chomp $nextline;
		while ($nextline !~ m/[A-Z][A-Z][A-Z][A-Z]/)
			{
			$nameline .= $nextline;
			$nextline = <COMPOUND>;
			chomp $nextline;
			}
		my $names = substr ($nameline, 12);
		while($names =~ m/\s{2}/)
			{ #Removes all but single spaces
			$names =~ s/\s{2,}//;
			} 
		my @names = split(/;/, $names); #Split each name
		
		my $preferredname;
		
		foreach my $alternativename (@names) 
		{
		if ((! (defined ($preferredname))) or (length($preferredname) > length($alternativename) + 10))
			{
			$preferredname = $alternativename;
			}
		print MGN "$CompoundID\t$alternativename\n"; #Print each name
		}
		print PGN "$CompoundID\t$preferredname\n"; #Print preferred name
		}
	if ($line =~ m/\/\/\// and $nonameflag == 1)
		{
		#print "$CompoundID has no name\n";
		print MGN "$CompoundID\tGlycan $CompoundID\n";
		print PGN "$CompoundID\tGlycan $CompoundID\n";
		}
	}

print " Done.\n";

close COMPOUND;
close MGN;
close PGN;

#Now adding the checkbalanced.pl script
print "Checking that equations are balanced...";

use strict;
#use warnings;

#open reaction and preferred compound name files
open(REACTIONS, "parseKEGGreactionfileOUT.txt");
open(COMPOUNDS, "preferredcompoundname.txt");

my $line;
my @splitline;
my %reactequation;
my %compoundformula;

#populate hashes of reaction ID -> equation and compound ID -> formula
while(<REACTIONS>)
	{
	$line = $_;
	chomp $line;
	@splitline = split(/\t/,$line);
	$reactequation{$splitline[0]} = $splitline[3];
	}
	
while(<COMPOUNDS>)
	{
	$line = $_;
	chomp $line;
	@splitline = split(/\t/,$line);
	$compoundformula{$splitline[0]} = $splitline[2];
	}
	
#check that the hashes populated correctly
# open(EQUATIONS, ">equations.txt");
# open(FORMULAS, ">formulas.txt");
# foreach my $key (keys (%reactequation))
	# {
	# print EQUATIONS "$key\t$reactequation{$key}\n";
	# }
	
# foreach my $key (keys (%compoundformula))
	# {
	# print FORMULAS "$key\t$compoundformula{$key}\n";
	# }

my $reacteq;	
my $compform;

#Split equations into reactants and products as compound IDs
my @equation;
my %reactants;

my %products;

foreach my $key (keys %reactequation)
	{
	@equation = split(/ <=> /, $reactequation{$key});
	$reactants{$key} = $equation[0];
	$products{$key} = $equation[1];
	}

#check that productsformula hashes are correctly populated
# open (SPLITCHECK, ">splitcheck.txt");
# foreach my $key (sort keys %reactants)
	# {
	# print SPLITCHECK "$key\treacs=$reactants{$key}\tprods=$products{$key}\n";
	# }

#Second technique at replacing compounds IDs with formulas for reactants and products
my %reactantsformula;
my @compoundhits;
my $concatenatedformula;
foreach my $reacID (sort keys %reactants)
	{
	my $reactantset = $reactants{$reacID};
	@compoundhits = ($reactantset =~ m/(\d{0,}\s{0,1}\w{1}\d{5})/g);
	foreach my $key (@compoundhits)
		{
		$key =~ m/(\d{0,})\s{0,1}(\w{1}\d{5})/;
		my $number =1;
		if ($1){$number=$1}; 
		#print "reac-$reacID\tkey=$key\t";
		my $formulalookup = $compoundformula{$2};
		$concatenatedformula .= $formulalookup x $number; #concatenate up all the reactants to a single long string representing the formula
		#print "number=$number\tformula=$concatenatedformula\n";
		}
	$reactantsformula{$reacID}=$concatenatedformula;
	$concatenatedformula=(); #clear the monster formula
	}

my %productsformula;	
foreach my $reacID (sort keys %products)
	{
	my $productset = $products{$reacID};
	@compoundhits = ($productset =~ m/(\d{0,}\s{0,1}\w{1}\d{5})/g);
	foreach my $key (@compoundhits)
		{
		$key =~ m/(\d{0,})\s{0,1}(\w{1}\d{5})/;
		my $number =1;
		if ($1){$number=$1}; 
		#print "reac=$reacID\tkey=$key\t";
		my $formulalookup = $compoundformula{$2};
		$concatenatedformula .= $formulalookup x $number; #concatenate up all the reactants to a single long string representing the formula
		#print "number=$number\tformula=$concatenatedformula\n";
		}
	$productsformula{$reacID}=$concatenatedformula;
	$concatenatedformula=();
	}
	
	
#check whether reactions are balanced and output a list
open (BALANCED, ">reactionbalancedcheck.txt");
print BALANCED "Reaction ID\tReactant Atoms\tProduct Atoms\tBalanced\n";
my $balancedbool;
foreach my $key (sort keys %reactantsformula)
	{
	my $reactantatoms = &listofatoms($reactantsformula{$key});
	my $productsatoms = &listofatoms($productsformula{$key});
	if ($reactantatoms eq $productsatoms)
		{
		$balancedbool = "True";
		}
	else
		{
		$balancedbool = "False";
		}
	if ($key !~ m/Reaction Number/) #cheeky hack to get of the last entry
		{
		print BALANCED "$key\t$reactantatoms\t$productsatoms\t$balancedbool\n";
		}
	}

print "Done!";
#Replace compoundIDs with formulas for reactants and products
#This technique didn't work too well.

# my %reactantsformula; #not yet implemented
# my %productsformula; #not yet implemented
# my @splitreactants;
# my @splitproducts;
# foreach my $key (keys %reactants) #populate array of individual reactants and products
	# {
	# @splitreactants = split(/ + /, $reactants{$key});
	# @splitproducts = split(/ + /, $products{$key});
	# foreach my $compoundID (@splitreactants) #replace each compoundID with compound formula
		# {
		# $reactantsformula{$key} .= $compoundformula{$compoundID};
		# }
	# foreach my $compoundID (@splitproducts) #replace each compoundID with compound formula
		# {
		# $productsformula{$key} .= $compoundformula{$compoundID};
		# }
	# }
	
#check that productsformula hashes are correctly populated
# open (FORMULACHECK, ">formulacheck.txt");
# foreach my $key (sort keys %reactantsformula)
	# {
	# print FORMULACHECK "$key\t$reactantsformula{$key}\t$productsformula{$key}\n";
	# }

#Split formulas into numbers of atoms, now made into a subroutine that returns a sorted string
sub listofatoms
	{
	my @atoms;
	my $atom;
	my %reactantatoms;
	my $atomname;
	my $atomnumber;
	my $returnvalue;

	$atom = shift; #take input from argument of subroutine
	@atoms = ($atom =~ m/([A-Z]{1}[a-z]{0,1}\d{0,})/g); #oh yes this construct is 
	foreach my $atom2 (@atoms) #split atoms into names and numbers and add the numbers cumulatively
		{
		$atomnumber = 1; #assume 1 atom until a digit is found
	
		if($atom2 =~ m/(\d+)/)
			{
			$atomnumber = $1;
			}		
		$atom2 =~ m/([A-Z]{1}[a-z]{0,1})/; 
		$atomname = $1;
		if($atomnumber =~ m/\d/)
			{
			$reactantatoms{$atomname} += $atomnumber;
			}
		else
			{
			print "error with atomnumber = $atomnumber\n";
			}
			
		}
	foreach my $key (sort keys %reactantatoms)
		{
		$returnvalue .= "$key$reactantatoms{$key} ";
		}
	%reactantatoms = (); #clears hash at the ned of loop
	return $returnvalue;
	}
