% Jon Newman
% Ga Tech

% 15 Apr 2010

% Finds PSC times in data. Creates PSC snips. Appends this information to
% the data file (as a new field) and resaves

% Parameters defining PSC
% *************************************************************************
dirID = 'C:\TempData\20100409\20100409-1\';
dirdat = dir(strcat([dirID '*.mat']));
rmsfac = 3.5; % times RMS
minsep = 1; % minimum peak separation in ms
rmswind = 500; %ms
% *************************************************************************

for j = 1:size(dirdat,1)
    
    fid = dirdat(j).name;
    load(strcat([dirID fid]));
    
    if isfield(data,'arasid') && ~ischar(data.arasid.iart)
        curr =  data.arasid.iart;
    else
        curr =  data.intrarec.imon;
    end
    
    psc = cell(1,size(curr,2));
    pscplot = [];
    
    Fs = data.sampfreq;
    minsepsamp = floor((minsep/1000)*Fs);
    rmswindsamp = floor((rmswind/1000)*Fs);
    
    
    % Find PSC times and amplitudes
    for i = 1:size(curr,2)
        
        samp = curr(:,i);
        reclen = length(samp);
        if rmswindsamp<reclen
            numwind = floor(reclen/rmswindsamp);
        else
            numwind = 1;
        end
        locstemp = [];
        pkstemp = [];
        
        for k = 1:numwind
            if k ~=numwind
                sampseg = samp(1+(k-1)*rmswindsamp:k*rmswindsamp);
            else
                sampseg = samp(1+(k-1)*rmswindsamp:end);
            end
            minamp = rmsfac*sqrt(mean(samp.^2));
            [pospks poslocs] =  findpeaks(sampseg,'minpeakheight',...
                minamp,'minpeakdistance',minsepsamp);
            [negpks neglocs] =  findpeaks(-sampseg,'minpeakheight',...
                minamp,'minpeakdistance',minsepsamp);
            pks = [pospks -negpks];
            locs = [poslocs neglocs];
            [locs sortind] = sort(locs);
            locstemp = [locstemp locs+(k-1)*rmswindsamp];
            pkstemp = [pkstemp pks(sortind)];
        end
        psc{i} = [locstemp' pkstemp'];
        pscplot = [pscplot;psc{i}];
        
    end
    
    data.psc.coords = psc;
    disp(strcat(['Found PSCs. Re-saving file as: ' fid]));
    save(strcat([dirID fid]),'data');
    
    figure()
    hold on
    plot(curr)
    plot(pscplot(:,1),pscplot(:,2),'k*')
    findfigs
end

