clear
close all
clc

matfiles = dir('*.mat');

% output data
headers = {'sample', 'Voltage [V]', 'Mean Displacement [mm]', 'std', 'Mean Charge [uC]', 'std', 'Mean Discharge [uC]', 'std'};
xlsdata = cell(length(matfiles)+1, 8);
xlsdata(1, :) = headers;

%voltage output pattern (on/off)
Vout = [zeros(2000, 1); ones(2000, 1); zeros(2000, 1); ones(2000, 1); zeros(2000, 1); ones(2000, 1); zeros(2000, 1)];
errThrsh = 14000 * 20;

for i = 1:length(matfiles)
    fname = matfiles(i).name;
    load(fname);
    
    sampleName = fname(17:end-10);
    sampleName(sampleName == '_') = ' ';
    regexMatch = regexp(fname, '\d+V', 'match');
    strMatch = regexMatch{1};
    voltage = str2double(strMatch(1:end-1));
    
    xlsdata(i+1, 1:2) = {sampleName, voltage};
    
    disp = 10 * data(:, 1); % displacement readings [mm] (*10 to correct for wrong laser sensor settings)
    Vin = 500 * data(:, 2); % voltage readings [V]
    Iin = 20 * data(:, 3); % current readings [uA]
    
    %% sort out membrane failures
    
    % only half because two channels
    Vcomp = Vout * (0.5 * voltage); % theoretical voltage output to compare to
    err = sum(abs(Vin - Vcomp));
    
    if err > errThrsh
        % mark as failed
        xlsdata{i+1, 3} = 'failed';
        % leave other cells in that row empty
        continue;
    end
    
    %% extract data
    nCycles = 6;
    eDisp = zeros(6, 1);
    eI = zeros(6, 1);
    for n = 1:nCycles % 3 cycles --> 6 'events'
        idx = n * 2 * 1000; % voltage switches every 2 s (2k samples)
        eI(n) = sum(Iin(idx:idx+1000)) / 1000; % sum I over one s when voltage switches, divide by 1000 because one sample = 1/1000 s
        
        idx = idx + 1500; % wait 1.5 s after voltage switches
        eDisp(n) = mean(disp(idx:idx+500)); % average disp over 0.5 s
    end
    
    eI = eI * 2; % because it's split between two channels
    
    meanDisp = mean(eDisp([2 4 6]) - eDisp([1 3 5]));
    stdDisp = std(eDisp([2 4 6]) - eDisp([1 3 5]));
    meanCharge = mean(eI([1 3 5]));
    stdCharge = std(eI([1 3 5]));
    meanDischarge = mean(eI([2 4 6]));
    stdDischarge = std(eI([2 4 6]));
    
    xlsdata(i+1, 3:8) = {meanDisp, stdDisp, meanCharge, stdCharge, meanDischarge, stdDischarge};
    
    %% plot
    
%     subplot(3, 1, 1)
%     hold off
%     plot(time, Vin);
%     hold on
%     plot(time, Vcomp);
%     title(sprintf('%s %iV', sampleName, voltage));
%     
%     subplot(3, 1, 2)
%     hold off
%     plot(time, Iin);
%     
%     subplot(3, 1, 3)
%     hold off
%     plot(time, disp);
%     
%     if err > errThrsh
%         set(gcf, 'Color', 'r');
%     else
%         set(gcf, 'Color', [0.9 0.9 0.9]);
%     end
%     
%     waitforbuttonpress();
end

xlswrite('HV data', xlsdata);

