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

% File name
close all
figure
fid = 'multi-u_2012-04-02_hoss-r3_ollie_363_01';
s = loadspk([fid '.spk']);
d = loaddig([fid '.dig']);
ss = SqueakySpk(fid,s.meta.fs_Hz,1,s);
xlimit = [0 2500];

%% Decode dig file
b = dec2bin(d.state,32);
u = bin2dec(b(:,1:29))/10e6;
c = bin2dec(b(:,30:31));
t = bin2dec(b(:,32));

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

%% Find start and end time for all u
tu_on = [];
tu_off = [];
for i = 1:length(uu)
    tu_on = [tu_on d.time(find(u == uu(i),1, 'first'))];
    tu_off = [tu_off d.time(find(u == uu(i),1, 'last'))];
end


%% Calculate ASDR for whole record
ss.ASDR(0.1,[],[],[],[],0);

%% For each unique u in uu find the average firing rate 

% num detected units
nu = length(unique(ss.unit));
fru = [];
for i = 1:length(uu)
    fru = [fru mean(ss.asdr.asdr(ss.asdr.bin >= tu_on(i)+5 & ss.asdr.bin <= tu_off(i)))/nu];
end

% fr_nom = mean(ss.asdr.asdr(ss.asdr.bin >= 0 & ss.asdr.bin <= min(tu_on)))/nu;
fr_nom = mean(ss.asdr.asdr(ss.asdr.bin >= max(tu_on)+120))/nu;


uFR = [];
sFR = [];
db = 0.1;
bins = 0:db:0.9;

% bin results
for b = bins
    uFR = [uFR,mean(fru(uu>= b & uu < b + db))];
    sFR = [sFR,std(fru(uu>= b & uu < b + db))];
end

fru = smooth(fru,3);

%% Plot result
% figure
hold on
plot(uu, fru, 'o')
errorbar(bins+db/2,uFR,sFR,'k')
axis tight

% File name
% close all
fid = '../2012_03_30_Ollie-363_MultiClamp/multi-u_2012-03-31_hoss-r3_ollie_363_03';
s = loadspk([fid '.spk']);
d = loaddig([fid '.dig']);
ss = SqueakySpk(fid,s.meta.fs_Hz,1,s);
xlimit = [0 2500];

%% Decode dig file
b = dec2bin(d.state,32);
u = bin2dec(b(:,1:29))/10e6;
c = bin2dec(b(:,30:31));
t = bin2dec(b(:,32));

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

%% Halo
uu = u(u~=0 & c == 1);

%% Find start and end time for all u
tu_on = d.time(ismember(u,uu));
tu_off = tu_on + 20;

% %% Calculate ASDR for whole record
ss.ASDR(0.1,[],[],[],[],0);


%% For each unique u in uu find the average firing rate 

% num detected units
nu = length(unique(ss.unit));
fru = [];
for i = 1:length(uu)
    fru = [fru mean(ss.asdr.asdr(ss.asdr.bin >= tu_on(i) & ss.asdr.bin <= tu_off(i)))/nu];
end
[uuu ind] = sort(uu);
fru = fru(ind);
fru = smooth(fru,3);

% fr_nom = mean(ss.asdr.asdr(ss.asdr.bin >= 0 & ss.asdr.bin <= tu_on(1)))/nu;
fr_nom = mean(ss.asdr.asdr(ss.asdr.bin >= max(tu_on)+120))/nu;

uFR = [];
sFR = [];
db = 0.1;
bins = 0:db:0.9;

% bin results
for b = bins
    uFR = [uFR,mean(fru(uuu>= b & uuu < b + db))];
    sFR = [sFR,std(fru(uuu>= b & uuu < b + db))];
end

%% Plot result
hold on
plot(uuu,fru, 'yo')
errorbar(bins+db/2,uFR,sFR,'k')
plot([0 1],[fr_nom fr_nom],'k--')
set(gca,'Fontsize',12);
axis tight
xlabel('u','Fontsize',12)
ylabel('Hz/unit','Fontsize',12)

%%
export_fig multi-u_ollie_363_combine_2012_03_31-03_2012_04_02-01 -pdf -transparent
export_fig multi-u_ollie_363_combine_2012_03_31-03_2012_04_02-01 -r400 -transparent
