'''
Created on 28 Jun 2012

@author: flynns
'''

import argparse
import fileinput

'''
Build up the command currentLine and parse whatever we've been fed into
useful variables.
'''

parser = argparse.ArgumentParser(description='Checks and reformats pipe delimited files if necessary. Assumes the first line of the input file is correct')
parser.add_argument('file')
parser.add_argument('delimiter', default=",")
args = parser.parse_args()

print("value of file is", args.file)
print("value of the delimiter is", args.delimiter)

for currentLine in fileinput.input(args.file):
    if fileinput.isfirstline():
        targetWidth = currentLine.count(args.delimiter)
        print("I'm looking for ", targetWidth, args.delimiter, "in each currentLine...")

    if (currentLine.count(args.delimiter) != targetWidth):
        '''
        we have found a currentLine which isn't the correct length. We need to
        grab the next line from the original file and append it to the current
        currentLine.
        '''
        print("short line found at line", fileinput.filelineno())
        nextLine = fileinput.FileInput.readline(args.file)
        outputLine = currentLine + nextLine
        print("amended input line is: \n", outputLine)
    else:
        outputLine = currentLine
    '''
    Here we'd emit the outputLine, however it was built up...
    '''
    print(outputLine)

if __name__ == '__main__':
    pass
