% Jon Newman
% Multi-parameter activity assay for cultures transfected with
% optical exciters and silencers

% File name
close all
figure
fid = 'max-power-preserving-triangle_2013-12-16_hoss-r3_smiley_22568_01';
s = loadspk([fid '.spk']);
d = loaddig([fid '.dig']);

% Parameters
which_types = [6 7 8 9 10];
units = 1:30;
xlimit = [-10 100];

%% Decode dig file
b = dec2bin(d.state,8);
u = bin2dec(b(:,1:end-3));
c = bin2dec(b(:,end-2:end-1));
t = bin2dec(b(:,end));

stm.time = d.time(logical(t));
stm.channel = u(logical(t));
% stm.type = u(logical(t));

uu = unique(u(c == 0));
uu = uu(uu~=0);

%% Recreate the triangle stimuli
Vmax = 11.5;    % Volts
dt = 0.01; % DAC sample res. (ms)
T = [1.33 2 3 4 5 10 20 30 40 50]; % Triangle widths, ms

% Create triangle waveforms to apply
[tri, tri_time] = make_max_power_triangles_plot(T,Vmax,dt);

%% Make SS object
ss = SqueakySpk(fid,s.meta.fs_Hz,1,s,stm);
ss.RemoveChannel([1 8 33 57 64 35]);
ss.RemoveUnit(0);
ss.PeriStimHistogram(1,xlimit,[],0)

%% Plot responses
close all
f = figure('Units','centimeters','Position',[5 5 20 20]);
col = [
    [236 117 117];
%     [220 000 000];
    [255 102 000];
%     [255 205 041];
    [182 236 000];
%     [000 170 000];
    [000 170 212];
%     [000 100 255];
    [150 000 212];
%     [085 000 212];
    [102 102 102]
    ]/255;


a1 = axes('Units','centimeters','Position',[5 15 10 3]);
hold on
for i = 1:length(which_types)
    this_tri =  tri{which_types(i)};
    this_tri(this_tri < 0 ) = 0;
    plot([xlimit(1) 1000*(tri_time{which_types(i)}) xlimit(2)],[0 this_tri 0],'Color',[ 0 0 0]); % - max(tri_time{i})
end
ylabel('mW \cdot mm^{-2}','FontName','Arial','Fontsize', 7)
set(a1,'Xlim',xlimit,'TickDir','out','FontName','Arial','Fontsize', 7)


a = axes('Units','centimeters','Position',[5 11 10 3]);
hold on
for i = 1:length(which_types)
    
    plot(1000*ss.psh.t,ss.psh.hist(which_types(i),:)/numel(unique(ss.unit)),'Color',[ 0 0 0])
    
end
ylabel('Hz/unit','FontName','Arial','Fontsize', 7)
xlabel('Time (ms)','FontName','Arial','Fontsize', 7)
set(a,'Xlim',xlimit,'TickDir','out','FontName','Arial','Fontsize', 7)


for i = 1:length(which_types)
    
    these_stim = ss.st_channel == which_types(i);
    ss.UnitWisePSH(1,[-10 100],these_stim,units,100,[],1,0)
    a = axes('Units','centimeters','Position',[5 9-(i-1)*1.5 10 1]);
    ss.PlotUnitWisePSH(250,0);
    hold on
    plot([0 0],[0 max(ss.unit)],'k-')
    set(a,'XTick',[],'YTick',[],'FontName','Arial','Fontsize', 7)

    
    
end
c = colorbar('location','SouthOutside','FontName','Arial','Fontsize', 7);

saveas(gcf,[fid '_PSH'])
export_fig('-pdf','-transparent',[fid '_PSH2'])



