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

% File name
base = './';

fids = {
    'sine-wave_2013-12-16_hoss-r3_smiley_22568_01';
};

figure


for f = 1:length(fids);
    
    
    fid = fids{f};
    s = loadspk([base fid '.spk']);
    d = loaddig([base fid '.dig']);
    ss = SqueakySpk(fid,s.meta.fs_Hz,1,s);
    ss.RemoveUnit(0);
    ss.RemoveChannel([1 8 33 57 64]);
    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),'stable');
    uu = uu(uu~=0);
    
    %% Find start and end time for all u
    tu_on = d.time(logical(t));
    tu_off = tu_on + 60;
   
    
    %% Calculate ASDR for whole record
%     ss.ASDR(0.1,[],[],[],[],0);
    
    %% For each unique u in uu find the average firing rate
    spk = ss.ReturnClean();
    
    
    % num detected units
    nu = length(unique(spk.unit));
    fru = [];
    for i = 1:length(uu)
        these_spikes = sum(spk.time >= tu_on(i) & spk.time <= tu_off(i));
        fru = [fru these_spikes/nu/60];
    end
    
    % fr_nom = mean(ss.asdr.asdr(ss.asdr.bin >= 0 & ss.asdr.bin <= min(tu_on)))/nu;
    fr_nom = sum(spk.time >= 0 & spk.time <= tu_on(1))/tu_on(1)/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
    
    %% Plot result
    subplot(1,length(fids),f)
    plot(uu, fru, 'bo')
    hold on
    plot([0 1],[fr_nom fr_nom],'k--')
    set(gca,'Fontsize',12,'TickDir','Out');
%     axis([0 1 0.001 100])
    axis square
    box off
    xlabel('u','Fontsize',12)
    ylabel('Hz/unit','Fontsize',12)
    
    
end
saveas(gcf,[fid '_FR-0-2-60s'])
export_fig('-pdf','-transparent',[fid '_FR-0-2-60s'])
