%% load data

dirID = 'C:\Users\Lab\Documents\mingfaifong\2013-05-03_ignignokt21369_0-14DIV_MEA_6well\'; % directory (remember \ at end)
fid = 'ignignokt21369_10DIV_MEA_02-2013-05-15-16-29-40';
loadspk([dirID fid '.spk']);

w(1,:) = [3 4 5 12 13 20 21 28 29];
w(2,:) = [7 14 15 16 22 23 24 30 31];
w(3,:) = [38 39 40 46 47 48 55 56 63];
w(4,:) = [36 37 44 45 52 53 60 61 62];
w(5,:) = [34 35 41 42 43 49 50 51 58];
w(6,:) = [2 9 10 17 18 19 25 26 27];

time = ans.time;
channel = ans.channel;
% unit = ans.unit;
meta = ans.meta;
waveform = ans.waveform;
threshold = ans.threshold;

save([dirID fid '.mat'],'time','channel','meta','threshold','fid');

%% concatenate files
% dirID = 'C:\Users\Lab\Documents\mingfaifong\2013-05-03_ignignokt21369_0-14DIV_MEA_6well\'; % directory (remember \ at end)
% fid1 = 'ignignokt21369_7DIV_MEA_02-2013-05-12-15-58-26';
% fid2 = 'ignignokt21369_7DIV_MEA_04-2013-05-13-15-52-16';
% x1 = load([dirID fid1 '.mat']);
% x2 = load([dirID fid2 '.mat']);
% 
% time = [x1.time; x2.time+max(x1.time)];
% channel = [x1.channel; x2.channel];
% threshold = [x1.threshold; x2.threshold];
% fid = [fid1 '_and_' fid2];
% 
% save([dirID fid '.mat'],'time','channel','threshold','fid');

%% generate asdr
clear t asdr
dt = 1;
bins = 0:dt:max(time);
asdr = zeros(6,length(bins));

for i = 1:6
    t{i} = time(ismember(channel,w(i,:))==1);
    asdr(i,:) = hist(t{i},bins)/dt;
end

%% plot asdr

close all;
figure(1)
set(gcf,'Position',[4 49 2410 768])

for i = 1:6
    subplot(6,1,i)
    hold on;
    stairs(bins/3600,asdr(i,:),'-k','LineWidth',1);
    ylabel('ASDR (Hz)');
end

for i = 1:6
    subplot(6,1,i);
    box off;
    xlim([0 24]);
    ylim([0 ceil(max(max(asdr))/10)*10]);
    set(gca,'FontSize',12,'XTick',0:2:24,'TickDir','out','TickLength',[0.004 0.025],'LineWidth',2)
end

xlabel('Time (hours)','FontSize',16);
subplot(6,1,1);
title(num2str(fid),'Interpreter','none');

%% plot raster

% close all;
figure(2)
set(gcf,'Position',[4 49 2410 768])

c = hsv(9);

for i = 1:9
    for j = 1:6
        subplot(6,1,j)
        hold on;
        t = time(ismember(channel,w(j,i))==1);
%         plot(t/3600,i*ones(size(t)),'.','MarkerSize',1,'Color',c(i,:));
        plot(t/3600,i*ones(size(t))+0.2*randn(size(t)),'.','MarkerSize',1,'Color',c(i,:));
    end
end

for i = 1:6
    subplot(6,1,i);
    box off;
    xlim([0 24]);
    ylim([0 10]);
    set(gca,'FontSize',12,'XTick',0:2:24,'TickDir','out','TickLength',[0.004 0.025],'LineWidth',2,'YTick',[1:1:9],'YTickLabel',[])
    ylabel('Channel');
    hold off;
end

xlabel('Time (hours)','FontSize',16);
subplot(6,1,1);
title(num2str(fid),'Interpreter','none');