import os, re

import numpy as np
import matplotlib.pyplot as plt
from scipy.io import savemat as sio_savemat

from tdms.tdms_file import TDMSFile

def read_file(analog_file, encoder_file):       
    # create the tdms file object & link to nilibddc.dll
    file = TDMSFile(bin_path = "C:\\Users\\mkemp\\Documents\\Python\\tdms\\bin")  # bin_path = location of nilibddc.dll

    # load the analog data
    file.open(file_name = analog_file )
    data, period, npoints = file.read()
    file.close()

    # load the encoder data
    file.open(file_name = encoder_file)
    encoder_data, period, npoints = file.read()
    file.close()

    # merge the two data sets and add a time array
    data['time'] = np.arange(npoints) * period
    data.update(encoder_data)  # merge dicts

    return data

def save_to_mat(file_name, data):
    sio_savemat(file_name, data)

if __name__ == "__main__":
    root = "C:\\Users\\mkemp\\Documents\\MATLAB\\galene calibration\\2019-04-02-15iterations\\"
    for file in os.listdir(root):
        if file.startswith('analog-') and file.endswith(".tdms"):
            timecode = re.match("analog-(.*).tdms",file).group(1)

            analog_file  = root + "analog-"  + timecode + ".tdms"
            encoder_file = root + "encoder-" + timecode + ".tdms"
            matlab_file  = root + "data-"    + timecode + ".mat"

            data = read_file(analog_file, encoder_file)
            save_to_mat(matlab_file, data)
