dirID = 'C:\Users\USER\Documents\mingfaifong\pre-2012 (need to sort)\2011-11-02_haruki17898_13-16DIV_MEA_TTX-CNQX-vehicle\spkfiles\';
fid = 'haruki17898_13-16DIV';
cd(dirID);

x1 = loadspk('haruki17898_13DIV_pre-drug.spk');
x2 = loadspk('haruki17898_13DIV_pre-drug_cont.spk');
x3 = loadspk('haruki17898_14DIV_treatment.spk');
x4 = loadspk('haruki17898_15DIV_treatment.spk');
x5 = loadspk('haruki17898_16DIV_wash4-cont.spk');
timestamps = [0 24*3600 48*3600];


time = [x1.time-max(x1.time)-max(x2.time); x2.time-max(x2.time); x3.time(x3.time<24*3600); x4.time(x4.time<24*3600)+24*3600; x5.time+48*3600];
channel = [x1.channel; x2.channel; x3.channel(x3.time<24*3600); x4.channel(x4.time<24*3600); x5.channel];
unit = [x1.unit; x2.unit; x3.unit(x3.time<24*3600); x4.unit(x4.time<24*3600); x5.unit];
threshold = [x1.threshold; x2.threshold; x3.threshold(x3.time<24*3600); x4.threshold(x4.time<24*3600); x5.threshold];
waveform = [x1.waveform x2.waveform x3.waveform(:,x3.time<24*3600) x4.waveform(:,x4.time<24*3600) x5.waveform];

save([fid '_waveforms.mat'],'time','channel','unit','timestamps','threshold','waveform','fid','-v7.3');

%% separate channels
clear x*
x.time = time;
x.channel = channel;
x.unit = unit;
x.threshold = threshold;
x.waveform = waveform;

uloc = strfind(fid,'_');
fid_pre = fid(1:uloc-1);
fid_post = fid(uloc+1:end);

for i = 1:6
    labels = {'A';'B';'C';'D';'E';'F'};
    excludechannels = [1 6 8 11 32 33 54 57 59 64];
    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];
    excludechannels = horzcat(excludechannels,w(~ismember(w,w(i,:)))');

    ind = find(ismember(x.channel,excludechannels)==0);
    time = x.time(ind);
    channel = x.channel(ind);
    unit = x.unit(ind);
    threshold = x.threshold(ind);
    waveform = x.waveform(:,ind);

    save([fid_pre labels{i} '_' fid_post '_waveforms.mat'],'threshold','time','channel','waveform','unit','fid');
end
