% Jon Newman
% Parse combo SS object
% 2012 05 24
% 2012 06 24 - added sort by unit firing rate and unit firing rate meta
% data.
% 2012.11.29
% 2013.02.21 version-4

function [ss, config] = make_combo_ss(config)

k = 0;
sobj = {};
dobj = {};

% Load existing files
if config.nodrug
    k = k + 1;
    config.rec_map{k} = 'nodrug';
    config.rec_fid_order{k} = config.nodrug_fid;
    sobj{k} = loadspk([config.here config.raw_path config.nodrug_fid '.spk']);
    dobj{k} = loaddig([config.here config.raw_path config.nodrug_fid '.dig']);
end

if config.cnqxap5
    k = k + 1;
    config.rec_map{k} = 'cnqx-ap5';
    config.rec_fid_order{k} = config.cnqxap5_fid;
    sobj{k} = loadspk([config.here config.raw_path config.cnqxap5_fid '.spk']);
    dobj{k} = loaddig([config.here config.raw_path config.cnqxap5_fid '.dig']);
    
end

if config.blocktail
    k = k + 1;
    config.rec_map{k} = 'blocktail';
    config.rec_fid_order{k} = config.blocktail_fid;
    sobj{k} = loadspk([config.here config.raw_path config.blocktail_fid '.spk']);
    dobj{k} = loaddig([config.here config.raw_path config.blocktail_fid '.dig']);
end

config.no_recs = k;

% Get stimulus start and end times, check to make sure everything is lining
% up
st = []; et = [];
for k = 1:length(dobj)
    st = [st dobj{k}.time(1)];
    et = [et dobj{k}.time(end-1)];
end

if  length(unique(st)) > 1
    error('Stimulation start times differ, so this approach needs some modificaiton');
elseif length(unique(et)) > 1
    error('Stimulation end times differ, so this approach needs some modificaiton');
end

config.stim_start_t_sec = st(1);
config.stim_end_t_sec = et(1);

% Smash data into one large structure - note that since the spike times are
% overlayed, stimulations should start at the same time for all protocols
% and thus we can get average firing rate information, across drugs
% conditions for three different epochs from this one structure: pre,
% during and post stimulation.
s.time = [];
s.channel = [];
s.unit = [];
s.waveform = [];
s.id = [];

for k = 1:length(dobj)
    
    s.time = [s.time; sobj{k}.time];
    s.channel = [s.channel; sobj{k}.channel];
    s.unit = [s.unit; sobj{k}.unit];
    s.waveform = [s.waveform sobj{k}.waveform];
    s.id = [s.id; k*ones(length(sobj{k}.time),1)]; % give each spike a recording id
    
end

% Combine all recordings in sigle SS object so that unit numbering is
% preserved during offline sorting
ss = SqueakySpk([config.here config.parse_path config.expID '_combo'] ,sobj{1}.meta.fs_Hz,1,s);

end


