% Jon Newman
% Ga Tech

% 15 Apr 2010

% Plots intracellular current and extracellular stimulus data that has been
% processed by my batch processing routines.

% Specify tank and block and plot parameters
% *************************************************************************
dirID = 'C:\TempData\20100409\20100409-1\';
dirdat = dir(strcat([dirID '*.mat']));
downsampfac = 15;
% *************************************************************************

figure()
legend1 = {}; c1 = 1;
legend2 = {}; c2 = 1;


for j = 1:size(dirdat,1)
    fid = dirdat(j).name;
    load(strcat([dirID fid]));
    
    tau = data.stimpara.tau;
    amp = data.stimpara.amp;
    
    if isfield(data.psc,'epscta')
        subplot(121)
        if ~isempty(data.psc.epscta) && ~sum(unique(isnan(data.psc.peripsctime))) && ~sum(unique(isnan(data.psc.epscta.sd)))
            hold all
            h = errorbar(1000*downsample(data.psc.peripsctime, downsampfac),...
                downsample(data.psc.epscta.wave, downsampfac),...
                downsample(data.psc.epscta.sd, downsampfac));
            hChildren = get(h, 'children');
            set(hChildren(1), 'linewidth',5)
            legend1{c1} = strcat(['Tau = ' num2str(tau) ', Amp = '  num2str(amp)]);
            c1 = c1+1;
        end
        subplot(122)
        if ~isempty(data.psc.ipscta) && ~sum(unique(isnan(data.psc.peripsctime))) && ~sum(unique(isnan(data.psc.ipscta.sd)))
            hold all
            h = errorbar(1000*downsample(data.psc.peripsctime, downsampfac),...
                downsample(data.psc.ipscta.wave, downsampfac),...
                downsample(data.psc.ipscta.sd, downsampfac),'LineWidth',5);
            hChildren = get(h, 'children');
            set(hChildren(1), 'linewidth',3)
            legend2{c2} = strcat(['Tau = ' num2str(tau) ', Amp = '  num2str(amp)]);
            c2 = c2+1;
        end
    else
        error('You have not yet found PSCTAs for these data. Please do this first.');
    end
end


% Plot labels
subplot(121)
title('EPSC-Triggered Stimulus Average')
ylabel('Stimulus (V)')
xlabel('Time Relative to EPSC (ms)')
legend(legend1,'Location','NorthWest')
subplot(122)
title('IPSC-Triggered Stimulus Average')
ylabel('Stimulus (V)')
xlabel('Time Relative to IPSC (ms)')
legend(legend2,'Location','NorthWest')


reply = input('Save Figure? [y/n]: ','s');
if isempty(reply)
    reply = 'y';
end

if reply == 'y'
    figdir = strcat([dirID 'AcrossParameters_' '_FIG']);
    figfid = 'PSC_Triggered_Average';
    if ~exist(figdir,'dir')
        mkdir(figdir);
    end
    saveas(h, strcat([figdir '\' figfid '.fig']))
    saveas(h, strcat([figdir '\' figfid '.jpg']))
end
