#!/usr/bin/env python
"""Module doctsring

Routine Name:  write_aftox_inputs.py

Desc:  This routine is run from the command line with two or more
       filenames as arguments, the files being a template file 
       (the first argument) and one or more WR legacy MARSS 
       Aftox input scenario files.  A new scenario file in the
       RSA MARSS format will be written for each legacy file
       given.

Arguments:

Name            I/O     Description
----            ---     -----------
filenames       In      First filename must be a template file, ie,
                        the comment strings used in the RSA MARSS
			Aftox scenario files, beginning with a !

			The second and succeeding filenames muxt be
			old legacy WR MARSS Aftox *.aftox_inp files,
			however, the second file may optionally be
			a list of *.aftox_inp files, one per line.

filenames.txt  Out	A new Aftox scenario file will be written
			for each .aftox_inp file given (with a .txt
			extension appended to the filename).
usage:

write_aftox_inputs.py [-hv|--help --verbose] <filename> <filename> [<filename>...]

Revision History:

Date         Name          Description
----         ----          -----------
02-15-2005   S.L. Arnold   Original implementation.
"""

##--------------------------------------
import re, string, sys

def main(argv):

    import os, getopt, sys

    # Data dictionary for mapping old lines to new
    map_dict = {1:2,
		2:1,
		3:3,
		4:4,
		5:5,
		6:6,
		7:31,
		8:32,
		9:33,
		10:34,
		11:35,
		12:12,
		13:19,
		14:20,
		15:21,
		16:14,
		17:15,
		18:16,
		19:17,
		20:39,
		21:13,
		22:38,
		23:36,
		24:37,
		25:11,
		26:29,
		27:10,
		28:8,
		29:7,
		30:9,
		31:18,
		32:22,
		33:23,
		34:24,
		35:25,
		36:26,
		37:27,
		38:28,
		39:30,
		40:40,
		41:41,
		42:42,
		43:43}

# Do the right thing with boolean values for all known Python versions.
    try:
        True, False
    except NameError:
        (True, False) = (1, 0)

    verbose = False
    debug = False

    try:
        args, filenames = getopt.getopt(argv[1:], "hvd", ["help", "verbose",
	"debug"])
    except getopt.error, msg:
        args = "dummy"
        print msg
        print "Usage: %s <templatename> <filename> [<filename> ...]" % (argv[0],)
        print " Processes old Aftox input files into RSA-MARSS scenario files."
        sys.exit(2)

    for o, a in args:
        if o in ("-h", "--help"):
            print __doc__
            sys.exit(0)
	if o in ("-v", "--verbose"):
            verbose = True
	if o in ("-d", "--debug"):
            debug = True

    if verbose:
        print "options =", args
        print "filenames =", filenames

    if not filenames:
        print "Please specify a template file and one or more legacy Aftox input files."

    template_filename = filenames[0:1]
    for filename in template_filename:
        if verbose:
            print "template file =", filename
	i = 1
	template_dict = {i:'dummy'}
	if debug:
	    print "Start debug output: full template dictionary:\n"
        for line in open(filename):
            template_dict[i] = line
	    i = i + 1

	if debug:
	    print template_dict.items()
	    print "End debug output: full template dictionary...\n"

    inp_files = filenames[1:]
    if verbose:
        print "first input filename =", inp_files[0:1]

    for filename in inp_files:
        try:
            infile = open(filename, "r")
	except IOError, err:
            if verbose:
                print "\nPlease check the name(s) of your input file(s)"
	    print "I/O error: ", err
            os.close(sys.stderr.fileno())
            sys.exit(2)
	except TypeError, err:
            if verbose:
                print "\nPlease check the name(s) of your input file(s)"
            print "Type error: ", err
            os.close(sys.stderr.fileno())
            sys.exit(2)

        try:
	    outfile = open(filename+".txt", "w")
	except:
            print "Unexpected filesystem error:", sys.exc_info()[0]
            raise
	if verbose:
	    print "first output filename =", outfile

	# Actually do something with the files - main processing loop

	try:
	    new_file_list = string.split(infile.readline())
	    if debug:
	        print "Start debug output: list of input file data:\n"
		print new_file_list
		print "End debug output: list of input file data...\n"
	    
	    j = 1
	    new_dict = {j:'dummy'}
	    if debug:
		print "Start debug output: new line data:\n"
            for line in new_file_list:         ## iterate through the file
	    				       ## lines by line,
	    				       ## process and write out new
					       ## format in new file

		map_value = map_dict.get(j)
		new_value = template_dict.get(map_value)
		temp_line = string.ljust(width=18,s=line)+new_value
		new_dict[map_value] = temp_line
		new_line = temp_line
		
		if debug:
		    print "New line =", new_line

		j = j + 1

	    if debug:
		print "End debug output: new line data:\n"
	    new_list = new_dict.values()
	    for k in new_list:
	        outfile.write(k)
	    outfile.write("01 JAN 1970 0000  ! date and time")
	    outfile.write('\n')

        except ValueError:                     ## the return from blank line
            if verbose:                        ## causes a ValueError here
                print "  Continuing with next available file..."
            continue                           ## this assumes a blank line
                                               ## only occurs at the end of
					       ## a data file
	#print template_dict.items()
	if verbose:
            print "last input file processed =", infile
	outfile.flush()
	outfile.close()

    infile.close()

if __name__ == "__main__":
    main(sys.argv)


