
function [bar_pos, bins]=make_bins(Ti,bins_per_decade,number_of_decades,t0,correction)

% INPUT ARGUMENTS:
%
% DWT_array: an array contaning all the dwell times (i.e.the time
% difference between successive crossings)
%
% Ti: gives the position of the left edge of the first bin.
%
% bins_per_decade: number of logarithmic bins per decade.
%
% number_of_decades: indicates the range of the histigram. 
% The total number of the bins is given by 
% number_of_decades*bins_per_decade+1. 
%
% t0: time resolution (inverse of camera frequency).
%
% correction: if correction = 1, correction of the bin positions.
%
% OUTPUT:
%
% bar_pos: an aray containing bin centers (in log space).
%
% hist: an aray containing the dwell time histogram.
%
% bins: an aray containing the bin edges.
%
% sum: the total integral of the histogram. Just to be sure that it is equal to 1. 



% Construction of the usual binning in log space
alpha=exp(log(10)/bins_per_decade);

% Nbins is the total number of bin edges
Nbins=number_of_decades*bins_per_decade+1;

bins=zeros([1,Nbins]);

% The bin edges are stored in the array "bins"

for n=1:Nbins
    bins(n)=Ti*alpha^(n-1);
end

% Correcting the bin sizes
if correction == 1
    
    bin_space=zeros([1,Nbins-1]);
% Calculation of the width of each bin and storing in the array  "bin_space"     
    for n=1:(Nbins-1)
        bin_space(n)=bins(n+1)-bins(n);
        
% Roundin of each bin width to the closest multiple of t0
% (the function "ceil" always rounds toward the larger integer)
    
        bin_space(n)=ceil(bin_space(n)/t0)*t0;
    end
    
% Similarly, the edge correction of the first bin
    
    bins(1)=ceil(bins(1)/t0)*t0;
    
% Reconstruction of the bin edges
    
    for n=2:Nbins
        bins(n)=bins(n-1)+bin_space(n-1);
    end
end

% Finally, calculating the center of each bin
% Since we are in log space, the bin center is the geometrical average of the two bins

bar_pos=zeros([1,Nbins-1]);

for i=1:Nbins-1
    
    bar_pos(i)=sqrt(bins(i)*bins(i+1));
    
end
