#!/usr/bin/env /usr/bin/ecell3-python

"""
A program for converting EM to EML.
This program is part of E-Cell Simulation Environment Version 3.
"""

__program__ = 'ecell3-em2eml'
__version__ = '0.1'
__author__ = 'Kentarou Takahashi and Koichi Takahashi <shafi@e-cell.org>'
__copyright__ = 'Copyright (C) 2002-2003 Keio University'
__license__ = 'GPL'


import sys
import os
import string 
import getopt
import tempfile

import ecell.emparser

def usage():
	aProgramName = os.path.basename( sys.argv[0] )
	print '''
%s -- convert em to eml

Usage: %s [-h] [-o outfile] [-p emlfile] infile.em

       By default this command automatically overwrite infile.eml.

Options:
        -h or --help       :  Print this message.
        -o or --outfile=   :  Specify output file name.  '-' means stdout.
	-p or --patch=     :  Patch source eml file
        -E or --preprocess :  Preprocessing only. implies -o -.
''' % ( aProgramName, aProgramName )
	


def main():

	try:
		opts , args = getopt.getopt( sys.argv[1:] , 'DEho:p:',
					     ["help", "outfile=",
					      "preprocess"])
	except:
		usage()
		sys.exit(1)

	anEmlFileName = None
	aForceFlag = 1 # Default Automatic overwrite mode
	aPatchFlag = 0
	debug = 0
	preprocessing_only = 0
	for anOption, anArg in opts:
		if anOption in ( "-h", '--help' ):
			usage()
			sys.exit(0)
			
		if anOption in ( "-D", '--debug' ):
			debug = 1
			
		if anOption in ( "-o", '--outfile'):
		        anEmlFileName = anArg
			
		if anOption in ( "-p", '--patch'):
			aPatchFlag = 1
			aSrcEmlFileName = anArg
			aSrcEmlFile = open( aSrcEmlFileName, 'r' )
			aSrcEml = ecell.eml.Eml( aSrcEmlFile)

		if anOption in ( "-E", '--preprocess'):
			preprocessing_only = 1
                        anEmlFileName = '-'			


        if len( args ) == 0:
		sys.stderr.write( "No input file.\n" )
		sys.exit( 1 )

	if args[0] == '-':
		anEmlFileName = '-'
		anEmFileName = args[1]
	else:
		anEmFileName = args[0]
		anEmFile = open( anEmFileName, 'r' )
	aBaseName = os.path.basename( anEmFileName )
	aBaseName, anExt = os.path.splitext( aBaseName )

	# <infile> check mode
	if anExt == '.eml':
		sys.stderr.write( "input file not .em file.\n" )
		sys.exit( 1 )

	if anEmlFileName == None:
		if anExt == '.em':
			anExt = '.eml'
		else:
			anExt += '.eml'

		anEmlFileName = aBaseName + anExt

	if anEmlFileName == '-':
		anEmlFile = sys.stdout

	aPreprocessor = ecell.emparser.Preprocessor( anEmFile, anEmFileName )
	aTempFile = aPreprocessor.preprocess()

	aTempFile.seek( 0 )

	if preprocessing_only != 0:
		anEmlFile.write( aTempFile.read() )
		aTempFile.close()
		anEmlFile.close()
		sys.exit(0)

	if aPatchFlag:
		anEmlObject = ecell.emparser.patchEm2Eml( aSrcEml, aTempFile, debug )
	else:
		anEmlObject = ecell.emparser.convertEm2Eml( aTempFile, debug )
		
	aTempFile.close()
	del aPreprocessor

	aString = anEmlObject.asString()
	
        if anEmlFileName == '-':
		print aString
	else:
		# Default automatic overwrite mode
		if os.path.isfile(anEmlFileName) and aForceFlag:
			pass
		
		elif not os.path.isfile(anEmlFileName):
			pass
		else:
			sys.stderr.write( "The output file already exists. To overwrite, use -f or --force.\n" )
			sys.exit( 1 )
			
		anEmlFile = open(anEmlFileName, 'w')
		anEmlFile.write(aString)
		anEmlFile.close()
		


if __name__ == '__main__':
	main()
