#!/usr/local/bin/perl 

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

# make sure input file is defined

if (1*@ARGV==0) { 
	print "No filename supplied.";
}

else {


# locate the file and define the output file

$INPUT_FILE = "@ARGV[0]" . ".mol";
$OUTPUT_FILE = "@ARGV[0]" . ".jme";

# make sure input file is present

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

else {


# read the input file into @array

open(INPUT_FILE);
@array = <INPUT_FILE>;
close(INPUT_FILE);

foreach (@array) {

$wholefile = $wholefile.$_;

}


# entire input file is now contained 
# in scalar variable $wholefile


############################
##   Sort out the input   ##
############################


    chomp($wholefile);
    chomp($wholefile);
    chomp($wholefile);
    chomp($wholefile);
    chomp($wholefile);

	# remove any Ź characters in the mol file
	$wholefile =~ s!Ź!!g;

	# Get rid of stuff at beginning of file
	$wholefile =~ s!(.)*(?=(\n\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([A-Za-z]+)[^\n]*\n))!Ź!x;
	$wholefile =~ s![^Ź]*Ź!!x;

	# Get rid of stuff at end of file
	$wholefile =~ s!((?=\n)\s+([\d]+)\s+([\d]+)\s+([\d\.]+)[^\n]*(?=(\n||$)))!\1Ź!gx;
	$wholefile =~ s!Ź[^Ź]*$!!;
	$wholefile =~ s!Ź!!g;

	$no_of_atoms=0;
	$no_of_bonds=0;            

	# Markup atom data
    	while (	$wholefile =~ m!(?=\n)\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([A-Za-z]+)[^\n]*(?=\n)!x){
	$no_of_atoms++;
    	$wholefile =~ s!(?=\n)\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([A-Za-z]+)[^\n]*(?=\n)
    		! \4 \1 \2!x;
	}

	# Markup bond data
    	while ($wholefile =~ m!(?=\n)\s+([\d]+)\s+([\d]+)\s+([\d\.]+)[^\n]*(?=(\n||$))!x){
			$no_of_bonds++;
	   		$wholefile =~ s!(?=\n)\s+([\d]+)\s+([\d]+)\s+([\d\.]+)[^\n]*(?=(\n||$))
    		! \1 \2 \3!x;
	}

	# add total atoms & bonds to the beginning
	$wholefile =~ s!^!@ARGV[1],"$no_of_atoms $no_of_bonds!x;
	$wholefile =~ s!$!"!x;
 	

# write the final version to file

open(OUTPUT_FILE,">$OUTPUT_FILE"); 
print OUTPUT_FILE "molfile";
print OUTPUT_FILE ($wholefile);
close(OUTPUT_FILE)
#

}
}
