#!/usr/bin/python

"""
Check timestamps of i2b files against proglog
Usage: fix_i2b_timestamps.py [rig nr] [test nr] [file specifying fixes]
    example: fix_i2b_timestamps.py 2 82 2test82_i2b_times_check_91_files_to_fix_0_choices.txt
    [file specifying fixes] is a space-delimited txt file created by check_i2b_timestamps.py
2011-06-16
updated	2012-08-09 to work with	older versions of python (2.2.3) due to	old elektrodetest server     
  and now automatically makes a backup copy of the impedance/raw/ folder before editing the i2b files.
@author: Chris Graves (cgra@dtu.dk) (christoph.graves@gmail.com)
"""

import sys
import os
import time

if len(sys.argv) < 4:
    print 'Usage: fix_i2b_timestamps.py [rig nr] [test nr] [file specifying fixes]'
    sys.exit(0)

rig_nr = sys.argv[1]
test_nr = sys.argv[2]

base_path = '/home/http/html/rig' + rig_nr + '/' + rig_nr + 'test' + test_nr + '/'
i2b_folder =  base_path + 'impedance/raw/'
fixes_file = base_path + 'impedance/' + sys.argv[3]

fid = open(fixes_file, "r")
fixes = fid.readlines()
fid.close()

currtime = time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())
backup_i2b_folder = base_path + 'impedance/raw_backup_' + currtime + '/'
print 'Backing up ' + i2b_folder + ' to ' + backup_i2b_folder
os.system('cp -rp ' + i2b_folder + ' ' + backup_i2b_folder)

result_col = 0
filename_col = 1
i2b_datetime_col = 2
proglog_datetime_col = 3
i2b_utime_col = 4
proglog_utime_col = 5
seconds_to_add_col = 6

for i in xrange(1,len(fixes)):
    currfix = fixes[i].split()
    if currfix[result_col] == 'FIX!':
        filename =  i2b_folder + currfix[filename_col]
        fid = open(filename, "r")
        s = fid.read()
        fid.close()
        s = s.replace(currfix[i2b_datetime_col], currfix[proglog_datetime_col])
        s = s.replace(currfix[i2b_utime_col], currfix[proglog_utime_col])
        fid = open(filename, 'w')
        fid.write(s)
        fid.close()
        print currfix[filename_col] + ' edited.'
        # It will always say edited even if it failed, because try and except don't seem to work on celletest server Python installation

