#       DUNDEE_OUTPUT_SPLIT Split the output of ezr2dundee.py to multiple files (a single file contains ONE participant's fixations when she is reading ONE text)
# Usage: python dundee_output_split.py <all_file> <path>(e.g. python dundee_output_split.py  'dundee_output.txt' './ezrfiles/') 
#   all_file        is the txt file generated by ezr2dundee.py
#   path            is a directory where you want to save the multiple dundee-like files


import argparse

parser = argparse.ArgumentParser(description='Split dundee files.')
parser.add_argument('all_file', help = 'generated by ezr2dundee.py')
parser.add_argument('path', help = 'the output mutiple files go')
args = parser.parse_args()

class Fixation:
    def __init__(self, line):
        self.ppt = int(line[0])
        self.text = int(line[1])
        self.word = line[2]
        self.screennum = int(line[3])
        self.linenum = int(line[4])
        self.olen = int(line[5])
        self.wlen = int(line[6])
        self.xpos = int(line[7])
        self.wordnum = int(line[8])
        self.fdur = int(line[9])
        self.oblp = int(line[10])
        self.wdlp = int(line[11])
        self.laun = int(line[12])
    def pretty_print(self):
        return(' '.join([str(self.ppt), str(self.text),
                         str(self.word), str(self.screennum), str(self.linenum), 
                         str(self.olen), str(self.wlen), str(self.xpos), 
                         str(self.wordnum), str(self.fdur), str(self.oblp), 
                         str(self.wdlp), str(self.laun)]))
path = args.path
filename = args.all_file
header = True
fixes = []

with open(filename) as rf:
    for line in rf:
        if header:
            header = False
            continue
        fix = Fixation(line.split())
        fixes.append(fix)

### split fixes into subfiles
p = 0 ## current ppt
t = 0 ## current text
fn = path + 's' + str(p) + '00' + 'ma1p.dat'
wf = open(fn,'w')
wf.write("ppt text word screennum linenum olen wlen xpos wordnum fdur oblp wdlp laun\n")

for i in range(len(fixes)):
    fix = fixes[i]
    if fix.ppt == p and fix.text == t:
        wf.write(fix.pretty_print() + '\n')
    else:
        wf.close()
        p = fix.ppt
        t = fix.text
        textstr = str(t)
        if t < 10:
            textstr = '0' + str(t)
        fn = path + 's' + str(p) + textstr + 'ma1p.dat'
        wf = open(fn,'w')
        wf.write("ppt text word screennum linenum olen wlen xpos wordnum fdur oblp wdlp laun\n")
        wf.write(fix.pretty_print() + '\n')
wf.close()
