close all
clc
format longg

inputPath = ".\Bsp1Coriolis.txt";
outputPath = ".\CoriolisGoodFormat.csv";

Table=readtable(inputPath, 'VariableNamingRule','preserve');

time = Table(:,2);
secs = Table(:,3);

%channel identification
channels = Table.Properties.VariableNames;
channels = string(channels)';
channels(1:3) = [];

data = Table(:,4);

%time conversion
time = table2array(time);
secs = table2array(secs);

connectArrays = strcat(time, secs);
timeArray = datetime(connectArrays, 'InputFormat', 'HH:mmss,SSS');
timeArray.Format = 'mm:ss.SSS';

times = double(convertTo(timeArray,'epochtime', 'Epoch', timeArray(1), 'TicksPerSecond', 1000)) ./ 1000.0;

%convert column to array 
arrayData = times;

for channel = 1: length(channels)
    data = table2array(Table(:, 3 + channel));
    data = strrep(data, ',', '.');
    data = str2double(data);

    if ~isnan(data)
        arrayData = cat(2, arrayData, data);
    end
end

% read header because read table can't handle spaces in channel name
fid = fopen(inputPath);
% Read all lines & collect in cell array
txt = textscan(fid,'%s','delimiter','\n'); 
% Read header Line
Val = txt{1}(1);
headers = Val{1};
headers = split(headers);

%fix units
headerNames = [];
count = 1;

for header = 3: length(headers)

    if headers{header}(1) ~= '(' && strcmp(headers{header}, 'Mass')
        % Special rule for "Total Mass", since the space is horrible
        headerNames{count-1} = strcat(headerNames{count-1}, headers{header});
    elseif headers{header}(1) ~= '('
        headerNames{count} = headers{header};
        count = count + 1;
    end
end

headerNames = cell2mat(join(headerNames, ";"));

fid = fopen(outputPath, "wt");
fprintf(fid, '\n');
fprintf(fid, '\n');
fprintf(fid, headerNames);
fprintf(fid, '\n');

writematrix(arrayData, outputPath, 'WriteMode', 'append', 'Delimiter', ';');

fclose('all');
