#!/usr/local/bin/python
"""
Feb.  5, 2005, Dr. Brian Fristensky, University of Manitoba


 Description: Convert a file of tokens to a GDE
 flat file. The input file contains a single nonblank
 string on each line.

 Synopsis: list2flat.py infile outfile

 Files: infile      file of tokens

        outfile     GDE flat file, containing a comma separated
                    list of tokens

@modified: May 26 2010
@author: Dale Hamel
@contact: umhameld@cc.umanitoba.ca
"""

import os
import sys

blib = os.environ.get("BIRCHPYLIB")
sys.path.append(blib)

from birchlib import Birchmod
from birchlib import Argument

PROGRAM = "list2flat.py "
USAGE = "\n\tUSAGE: list2flat.py infile outfile"
BM = Birchmod(PROGRAM, USAGE)

class Parameters:
	
    def __init__(self):
        """
     		Initializes arguments:
     			IFN=""
     			OFN=""
     		Then calls read_args() to fill in their values from command line
     		"""
        self.IFN = ''
        self.OFN = ''
        self.read_args()
	
    def read_args(self):
        """
     		Read command line arguments into a Parameters object
     		"""
        infilename = Argument("", str, BM)
        outfilename = Argument("", str, BM)
	
        infilename.set_position(1)
        outfilename.set_position(2)
	
	
        try:
            self.IFN = infilename.fetch()
            self.OFN = outfilename.fetch()
        except:
            BM.printusage()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

def GETLIST(FN):
    """
    Read in old and new strings, striping 
    leading and trailing whitespace, including
    newline characters.
    """	
    LST = []
    try:
    	FILE = open(FN, 'r')
    except:
    	BM.fileError(FN)
    for LINE in FILE:
        # remove leading and trailing whitespece and newlines
	# before adding to the list
        TOKEN = LINE.strip()
        LST.append(TOKEN)

    FILE.close()
    return LST


 
def WRITEGDELIST(OUTFILE, LST):
    """
    Write the list as a single line of comma-separated values
    """	
    if len(LST) > 0:
        LINE = LST[0]
        for i in range(1, len(LST)):
            LINE = LINE + "," + LST[i]
        LINE = LINE + '\n'

        OUTFILE.write(LINE)
	
    
#======================== MAIN PROCEDURE ==========================


def main():
    """
     	Called when not in documentation mode.
     	"""
    P = Parameters()
	
	
    OUTFILE = open(P.OFN, 'w')
	
    # Read in list of tokens
    if os.path.exists(P.IFN):
        IDLIST = GETLIST(P.IFN)
	
        # The first line of a GDE flatfile is the a name line
        # beginning with the double quote character "
        NAMELINE = '"' + P.IFN + '\n'
        OUTFILE.write(NAMELINE)
	
        #Write the list as a single line of comma-separated
        # values
        WRITEGDELIST(OUTFILE, IDLIST)
	
    OUTFILE.close()
	
    BM.exit_success()

if (BM.documentor() or "-test" in sys.argv):
    pass
else:
    main()
