clear all;
close all;

%|| Modify these items to specify cell of interest and location of files
cultureID = 'hamhock3';     % <-- culture name, change once per dataset
dat.meta.cellNum = 14;      % <-- cell number, change each time you run script
dirID = ['\Documents and Settings\Annihilatrix II\Desktop\mingfaifong\HEKA data\' ...
    '2013-05-21_hamhock3_35DIV_Patch_OU-ChETA\']; % <-- parent directory, change once per dataset


%|| Potential stimulation protocols (any addition optical protocols should
%|| be listed before non-optical protocols (modify nonOptProt if necessary)
protocolList = {...
    'UpFreqChirp'; ...      %1
    'OU-Rep-5ms'; ...       %2
    'OU-Rep-50ms'; ...      %3
    'OU-Rand-5ms'; ...      %4
    'OU-Rand-50ms'; ...     %5
    'PBRS-1ms'; ...         %6
    'PBRS-10ms'; ...        %7
    'DownFreqChirp'; ...    %8
    'PowSteps'; ...         %9
    'CurrPulse'; ...        %10 (non-optical protocol)
    'HypCurrPulse'; ...     %11 (non-optical protocol)
    'LongCurr' ...          %12 (non-optical protocol)
    };
nonOptProt = 10; % denotes index where protocols become non-optical
                 % modify if adding more protocols to list


%%|| More cell & file location info (no modification necessary, probably)
if dat.meta.cellNum<10
    cellID = ['cell0' num2str(dat.meta.cellNum)];
elseif dat.meta.cellNum<100
    cellID = ['cell' num2str(dat.meta.cellNum)];
else
    disp('Were there really more than 99 cells?  Check file naming scheme.');
end
HEKAdirID = [dirID 'from_HEKA\' cellID '\'];


%|| Identifying mat files associated with specified cell
y = dir(HEKAdirID); z = [y.isdir];
fidlist = {y(~z).name};


%|| loop to go through all protocols for a specific cell
for j = 1:length(fidlist)
    clear Trace* x*
    
    %|| Loading mat file associated with specified cell
    fid = fidlist{j};
    load([HEKAdirID fid]);
   
    %|| Assigning names of all HEKA traces/sweeps to x
    x = who('Trace_*');
        
    %|| Loop to identify which protocol matches the opened file
    for k = 1:length(protocolList)
        if findstr(fid,protocolList{k})
            dat.meta.protocolType = protocolList{k};
            if k>=nonOptProt
                %|| Number of input streams for non-optical stim protocols
                %|| includes Vmem, Imem
                tmp_tracesPerSweep = 2;
            else
                %|| Number of input streams for optical stim protocols
                %|| includes V_mem, I_mem, V_photodiode, and I_LED)
                tmp_tracesPerSweep = 4; %for voltage clamp protocols
            end
            break;
        elseif k == length(protocolList)
            %|| If protocol is not on our list, then go to debug mode
            dat.meta.protocolType = 'unknown';
            disp('protocol not found');
            keyboard;
        else
            continue;
        end
    end
    
    %|| Number of sweeps = # of traces / # of input streams
    dat.meta.sweepTotal = length(x)/tmp_tracesPerSweep;
    
    %|| Reassigns 10th sweep to be after 9th sweep (instead of at beginning)
    if dat.meta.sweepTotal==10
        x = [x(5/4*tmp_tracesPerSweep:end); x(1:4/4*tmp_tracesPerSweep)];
    end
    
    %|| Identifies voltage or current clamp based on filename
    if findstr(fid,'_CC')
        dat.meta.controlType = 'Current Clamp';
        ctrl_tmp = 'CC';
    else
        dat.meta.controlType = 'Voltage Clamp';
        ctrl_tmp = 'VC';
    end
    
    %|| Identifies general meta data based file name
    uloc = findstr(fid,'_');
    dat.meta.date = fid(1:uloc(1)-1);
    dat.meta.culture = fid(uloc(1)+1:uloc(2)-1);
    dat.meta.HEKA.fileName = fid(1:uloc(3)-1);
    dat.meta.HEKA.groupName = fid(uloc(3)+1:uloc(4)-1);
    dat.meta.HEKA.seriesName = fid(uloc(4)+1:end-4);
    
    %|| Identifies series number based on filename
    dloc = findstr(dat.meta.HEKA.seriesName,'-');
    if length(dat.meta.HEKA.seriesName)-dloc(end)<=1
        seriesNum_tmp = ['0' dat.meta.HEKA.seriesName(dloc(end)+1)];
    else
        seriesNum_tmp = dat.meta.HEKA.seriesName(dloc(end)+1:dloc(end)+2);
        if seriesNum_tmp(2) == '_' || seriesNum_tmp(2) == '.'
            seriesNum_tmp = ['0' seriesNum_tmp(1)];
        end
    end
    dat.meta.HEKA.seriesNum = str2double(seriesNum_tmp);

    
    %|| loop to go through all sweeps (trials) of a single protocol
    for i = 1:dat.meta.sweepTotal
        
        %|| making data file name
        prefix_tmp = [cultureID '_' cellID '_' dat.meta.protocolType '_' ctrl_tmp '_' seriesNum_tmp];
        if length(num2str(i))==1
            dat.meta.name = [prefix_tmp '_00' num2str(i)];
        elseif length(num2str(i))==2
            dat.meta.name = [prefix_tmp '_0' num2str(i)];
        elseif length(num2str(i))==3
            dat.meta.name = [prefix_tmp '_' num2str(i)];
        end

        %|| getting I_mem and V_mem values
        x_Imem = eval(char(x(1+(tmp_tracesPerSweep*(i-1)))));
        x_Vmem = eval(char(x(2+(tmp_tracesPerSweep*(i-1)))));
        dat.raw.Imem = x_Imem(:,2);
        dat.raw.Vmem = x_Vmem(:,2);
        dat.meta.units.Imem = 'A';
        dat.meta.units.Vmem = 'V';

        %|| getting I_LED and V_photodiode values
        if tmp_tracesPerSweep==4
            x_Iled = eval(char(x(3+(tmp_tracesPerSweep*(i-1)))));
            x_Vpd = eval(char(x(4+(tmp_tracesPerSweep*(i-1)))));
            dat.raw.Iled = x_Iled(:,2);
            dat.raw.Vpd = x_Vpd(:,2);
            dat.meta.units.Vled = 'V';
            dat.meta.units.Iled = 'A';
            dat.meta.units.Ipd = 'A';
        end
        
        %|| getting more meta data
        dat.meta.fs_hz = 1/mean(diff(x_Imem(:,1)));
        tmp_tracename = char(x(1+(tmp_tracesPerSweep*(i-1))));
        uloc_tracename = findstr(tmp_tracename,'_'); 
        dat.meta.sweepNum = str2double(tmp_tracename(uloc_tracename(3)+1:uloc_tracename(4)-1));
        dat.meta.sweepLengthSec = max(x_Imem(:,1))-min(x_Imem(:,1));
        dat.meta.wasSweep = 1;
        
        %|| saving data file for a single sweep (trial) of the protocol
        save([dirID 'matfiles\' ...
            dat.meta.name '.mat'],'dat');

    end
    
end