% Script that reads SMUCS output files: Can take one or several files as
% input. All measurements are stored as a structure in a structure array.
% Each structure contains fields with measurement values and descriptive
% values
%
% dataSMU.time contains the delay to the very first measurment contained in
% the series in hours.


clearvars
close all

% USER INPUT HERE
formatIn = 'dd/mm/yyyy HH:MM:SS';

% Read Data
dirContent=dir('*.dat');
dataSMU=readData(dirContent,formatIn);


function dataSMU=readData(dirContent,formatIn)

dataSMU=[];
iM=0;

for m=1:length(dirContent)
    
    fileName = dirContent(m).name;
    disp(fileName)
    fid=fopen(fileName);
    
    tmp=textscan(fid,'%s',1,'delimiter','\n');
    lReading = true;
    iMStart = iM + 1;
    disp(iM);
    while lReading
        lNewData=false;
        tmp=textscan(tmp{1,1}{1,1},'%s %s %s %s %s %s %s %s');
        iM=iM+1;
        disp(iM);
        d.fileName=fileName;
        a=textscan(tmp{1,1}{1,1},'%s %s','Delimiter','#');
        d.measureType=a{1,2};
        a=textscan(tmp{1,2}{1,1},'%s %f','Delimiter','=');
        d.iMCycle=a{1,2};
        a=textscan(tmp{1,3}{1,1},'%s %f','Delimiter','=');
        d.iMux=a{1,2};
        a=textscan(tmp{1,4}{1,1},'%s %f','Delimiter','=');
        d.time=a{1,2};
        a=textscan(tmp{1,6}{1,1},'%s %s','Delimiter','=');
        d.refDate=strcat(a{1,2},{' '},tmp{1,7},{' '});
        a=textscan(tmp{1,5}{1,1},'%s %f','Delimiter','=');
        d.N=a{1,2};
        tmp=textscan(fid,'%s',1,'delimiter','\n');
        tmp=textscan(fid,'%f %f %f %f %f %f',d.N);
        %assign values to array
        NREAL=size(tmp{1,1});
        if NREAL(1)<d.N
            lReading = false;
            iM=iM-1;
        else
            d.V1=tmp{1,1};
            d.I1=tmp{1,2};
            d.t1=tmp{1,3};
            d.V2=tmp{1,4};
            d.I2=tmp{1,5};
            d.t2=tmp{1,6};
            
            dataSMU=[dataSMU d];
        end
        
        
        tmp=textscan(fid,'%s',1,'delimiter','\n');
        tmp=textscan(fid,'%s',1,'delimiter','\n');
        if isempty(tmp{1,1})
            lReading = false;
        end
            
    end
    
    fclose(fid);
end

[~,imin]=min(datenum([dataSMU.refDate]));

for i=1:length(dataSMU)
   
    dataSMU(i).time=(datenum(dataSMU(i).refDate,formatIn)-datenum(dataSMU(imin).refDate,formatIn))*24;
    
end

end



% calculate times
% [~,imin]=min(datenum(refDate));
% for i=1:length(refDate)
%     t1(:,i)=t1(:,i)+(datenum(refDate(i))-datenum(refDate(imin)))*24*60*60;
%     t2(:,i)=t2(:,i)+(datenum(refDate(i))-datenum(refDate(imin)))*24*60*60;
% end




