%----------------------------------------------------------------------
% Jon Newman
% February 25 2009
% April 13 2009
%
% MCD2SPKTIMES : .mcd file to spike times
%
% This M-File does the following:
%   >> Converts a .mcd file which has spike times to a vector of spike
%   times and a matrix of spike times versus electrode number
%
% USAGE:
% [spk_times mat_spk_times] = mcd2spkTimes(fid,startstop)
%           >> INPUT
%   fid = .mcd file with spike times
%   spkstrm = stream name for spike data
%   startstop = defines block of data to look at: [start_tic end_tic]
%           << OUTPUT
%   spk_times = spike times from start of recording 
%   channel = corresponding channel
%----------------------------------------------------------------------
function [spk_times channel] = mcd2spkTimes(fid,spkstrm,startstop)

spk_file = datastrm(fid); % get fid datastream handle

% supply default values
if nargin < 3 || isempty(startstop)
    len_record = getfield(spk_file ,'sweepStopTime');
    startstop = [0 len_record]; % default startstop block is whole record
end
if nargin < 2 || isempty(spkstrm)
    data_handle = getfield(spk_file,'StreamNames'); %attempt to get strm name
    spkstrm = cell2mat(data_handle);
end
if (nargin<1)
    error('provide an .mcd file for conversion yo!')
end

spk_data = nextdata(spk_file ,'streamname',spkstrm ,'startend',startstop);
cell_spk_times = spk_data.spiketimes;
chan = [];
for i = 1:length(cell_spk_times)
    chan = [chan; ones(length(cell_spk_times{i}),1)*i-1];
end
mat_spk_times = cell2mat(cell_spk_times);
[spk_times ind] = sort((1/1000)*squeeze(mat_spk_times)); %global array spike timing converted to seconds
channel = chan(ind);
end