%inputs:
%
%   n = length of one simulation run.
%   m = number of runs to average over.
%  timecourse = 0,1 telling us if we want to plot timecourses.
%
%output:
%
%  if timecourse=1, m realizations of length n. 
%
%   Example input: CLT1(10000,3,1)
%
%
%  if timecourse=0, a histogram. 
%
%   Example input: CLT1(10000,10000,0)

function [] = CLT1(n,m,timecourse)

tic

p=0.05;

if timecourse == 1
    S = zeros([m,n+1]);
    %generate m independent paths.
    for k = 1:m
        %generate the kth path.
        for i = 1:n
            r = rand;
            
            if r < p
                S(k,i+1) = S(k,i) + 1;
            else
                S(k,i+1) = S(k,i);
            end
        end
        
    end
    
    Tp = zeros([n+1,1]);
    for j = 1:n
        Tp(j+1) = Tp(j) +1;
    end
    
    hold on;
    for j = 1:m
        plot(Tp,(S(j,:)-p*Tp')/(sqrt(p*(1-p)*n)))
    end
    hold off;
    
    
else %timecourse == 0
    data = (binornd(n,p,m,1) - n*p)/sqrt(p*(1-p)*n);
    
    delta = .25;
    xn = -5:delta:5;
    
    %figure
    %hist(data,xn)
    
    bins = zeros([length(xn),1]);
    
    for ell = 1:m
        [t k] = min(abs(xn - data(ell)));
        bins(k) = bins(k) + 1;
    end
    sum(bins/m)
    for ell = 1:length(xn)
        Nor(ell) = (1/sqrt(2*pi))*exp(-xn(ell)^2/2);
    end
    figure
    hold on;
    bar(xn,bins/(m*delta),'red')
    plot(xn,Nor,'blue')
    hold off;
end

toc

end