function [rates,bins] = FiringRates(trains,maxtime,mintime,binlen,overlap)

% Calculates the firing rate of some group of spike trains according to a
% "binning" scheme, specified by the user.
% Input: trains = cell array (1 x m) with the spike train times of a 
%                 specific group.
%  max(min)time = maximum(minimum) spike time
%        binlen = time-length of bins
%         overl = bin overlap (in percentage)
% Output: rates = matrix with the rates (as columns)
%          bins = bins [starttimes endtimes]


cut = cellfun(@isempty,trains);                                             % Find any empty cells in the trains group
trains(cut)=[];                                                             % and remove them
m = length(trains);                                                         % Store the new length of the group

spikes = cellfun(@length, trains);                                          % Count the length of each spike train
maxspikes = max(spikes);                                                    % and find the longest spike train
Trains = zeros(maxspikes,m);                                                % Allocate memory for the MATRIX with the trains
for i=1:m
    Trains(1:spikes(i),i) = trains{i};                                      % Turn the cell into matrix (leaving zeros under the shorter trains)
end
clear trains spikes

binnum = ceil((maxtime - mintime - overlap)/(binlen - overlap));            % Calculate the number of bins needed.
rates = zeros(binnum,m);                                                    % Allocate memory for the firing rates
bins = zeros(binnum,2);                                                     % Allocate memory for the bin times [starttimes endtimes]

for i = 1:binnum                                                            % For each bin 
    bins(i,:) = [mintime + (i-1)*(binlen-overlap) , mintime + i*binlen - (i-1)*overlap];  % Set the start/endtimes
    count = histc(Trains, bins(i,:));                                       % Count the number of spikes within the bin in all trains.
    rates(i,:) = (count(1,:)+count(2,:))/binlen;                            % Calculate the firing rates
end                                                                         % (The 2nd row of "count" contains counts on bin(endtime) only,
                                                                            %  so it must be added to the 1st row)