###########################################################################
##
##   Python script for Motion Capture Data Parsing
##
##   VSFX 705 - Programming Concept - Exercise 3
##   with Professor Deborah R. Fowler
##
##   Student Name
##   Ziye Liu
##
##   Introduction
##        This Python script will take user's input, and find the motion
##        capture .txt file with it's folder, then create a new folder (if
##        needed) with the same name, then parse the data into 3D software
##        readable .txt sequence files.
##
##   Instruction on how to use it
##   
##       1. Put the original MoCap txt file in the same
##            directory with this script.
##       2. Run the script, follow the on screen instruction.
##
##   (C)Ziye Liu, 2013
##      www.ziyeliu.com
##      blog.ziyeliu.com
##
###########################################################################

import os


## let the user input the filename of raw mocap .txt file
print """
Please make sure you have put the original MoCap .txt file
in the same directory with this .py script.

Then
"""
filename = raw_input("Filename:")
##filename = "Aug210107"
fullfilename = filename + ".txt"

## check if a folder with the same name as the .txt file exists,
## if not, create one
if not os.path.isdir(filename):
    print "\nFolder does not exist, gonna create one..."
    createNewFolder = os.makedirs(filename)
    print "new folder created at:", "\\"+filename+"\\"


## if folder exists, then do the work:
print "\nFolder exists, and the motion capture file name is:\n", fullfilename


## open the raw .txt file to get the total line count
mocapRawFile = open(fullfilename, "r")
listMocap = mocapRawFile.readlines()
totalLine = len(listMocap)
print "\nFile opened with", totalLine, "lines."
print "\nWorking..."
mocapRawFile.close()


## re-open it for data parsing
mocapRawFile = open(fullfilename, "r")
## set the initial frame count number
frameCount = 0
## set the wrong value
wrongValue = -9999.99

for i in range (0, totalLine):
    ## read one line from the .txt file
    rawLine = mocapRawFile.readline()
    ## split this line into a list
    lineSplit = rawLine.split()


    ## test if the first character is digit (frame number)
    ## if it is, then do the work; if not, then ignore it.
    if lineSplit[0].isdigit() == True:
        
        ## grab the frame at 24fps
        if int(lineSplit[0]) % 5 == 0: # change to 0 for offset
            ## print frameCount
            ## set the output filename in format as:
            ##      ./filename/filename_parsed_#.txt
            outputFileName = "./" + filename + "/" + filename + "_parsed_" + str(frameCount) + ".txt"
            outputFile = open(outputFileName, "w")
            
            ## print rawLine
            ## get the total count of markers
            markerTotalNum = len(lineSplit)
            ## print "Parsing Line", lineSplit[0] + "..."##"\tLength:", markerTotalNum

            ## get x,y,z in the marker data, ignore the frame number and time code
            for j in range (0, markerTotalNum/3):
            ## print 1 + 3 * j, "\t", 3 + 3 * j, "\t", 2 + 3 * j
                increse = 3 * j + 1 #plus 1, skipping the time code
                ## print lineSplit[j]
                ## print j, lineSplit[1 + increse], lineSplit[2 + increse], lineSplit[3 + increse]           

                ## get rid of the wrong value -9999.99
                markerX = str(round(float(lineSplit[1 + increse])/100, 4))
                if float(markerX) == float(wrongValue/100):
                    markerX = str(round(float(lineSplit[1 + increse - 3])/100, 4))
                markerY = str(round(float(lineSplit[2 + increse])/100, 4))
                if float(markerY) == float(wrongValue/100):
                    markerY = str(round(float(lineSplit[2 + increse - 3])/100, 4))
                markerZ = str(round(float(lineSplit[3 + increse])/100, 4))
                if float(markerZ) == float(wrongValue/100):
                    markerZ = str(round(float(lineSplit[3 + increse - 3])/100, 4))
                    
                ## parse the data into correct format                   
                markersParsed = str(j) + " " + markerX + " " + markerY + " " + markerZ + "\n"
                ## write the parsed data into the destination .txt file
                outputFile.writelines(str(markersParsed))

            ## update the frame count number
            frameCount += 1
            outputFile.close()

        
print "\nDONE!!"
