#!/usr/bin/env python3
"""
January 4, 2006, Dr. Brian Fristensky, University of Manitoba

 Description: Convert a GDE flat file to a file of trees."

 Synopsis: flat2tree.py infile outfile"

 Files: infile      GDE flat file, containing one tree per line

       outfile     file of trees

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

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

from birchlib import Birchmod
from birchlib import Argument

PROGRAM = "flat2tree.py: "
USAGE = "\n\t USAGE: flat2tree.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):
        """
     		Reads command line arguments into a Paramter object
     		"""
		
        infile = Argument("", str, BM)
        outfile = Argument("", str, BM)
		
        infile.set_position(1)
        outfile.set_position(2)
		
        try:
            self.IFN = infile.fetch()
            self.OFN = outfile.fetch()
			
        except ValueError:
            BM.printusage()
		
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

def get_trees(FN):
    """
    Read in old and new strings, striping 
    leading and trailing whitespace, including
    newline characters.
    """
    try:
    	in_file = open(FN, 'r')
    except:
    	BM.file_error(FN)
    # skip name line
    line = in_file.readline()
    trees = []
    # GDE wraps the flat file with newlines every 60
    # characters. 
    # Therefore, we read through the file, ignoring any name
    # lines which begin with (") and concatenating lines
    # together, until the line read ends in (;), indicating
    # the end of a tree. We add this bigline to TREES, and
    # reset bigline to empty.
    bigline = "" 
    
    for line in in_file:
        line = line.strip()
        if  line.startswith('\"'):
            pass
        else:
            bigline = bigline + line
            if bigline.endswith(';'):
                trees.append(bigline)
                bigline = ""
	  
  

    in_file.close()
    return trees

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def writetreefile(P, OUTFILE, trees):
    """
    Write one tree per line
    """	
    if len(trees) > 0:
        for t in trees:
            line = t.strip()
            if line != "":
                line = line + '\n'
                OUTFILE.write(line)

    
#======================== MAIN PROCEDURE ==========================

#---------- Set global variables
def main():
    """
     	Called when not in documentation mode.
     	"""
    P = Parameters()
	
    OUTFILE = open(P.OFN, 'w')
	
    if os.path.exists(P.IFN):
	
        # Read in GDE flat file containing trees
        trees = get_trees(P.IFN)
	
        #Write one tree per line, stripping out the names
        writetreefile(P, OUTFILE, trees)
	
    OUTFILE.close()
	
    BM.exit_success()

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

