%HITTING A TILTED LINE

a=1; b=-1; %line is a+bt
n=10000; %no. of trajectories 
%if n>100, trajectories are not drawn
%instead empirical and true density are compared
%n=100;
hv=zeros(1,n);

%%% parameters
dt=0.001;
T=5;
t=[0:dt:T];

clf reset;

 
for (x0=[1:1:n])

   Bmt = cumsum(sqrt(dt)*randn(size(t)));
   line=a+b*t; 
   
   if (a>0)
      [dum, ind]=max(Bmt>line);
   else 
      [dum, ind]=max(Bmt<line);
   end 
   
   hv(x0)=ind*dt;
   
   if (n<=100)
       plot(t,Bmt,'Color',[0 x0/n 1]);
       hold on; 
   end

end
if (n<=100)
    plot(t, line, 'Color',[0 0 0]);
    plot(hv,a+b*hv, 'o', 'MarkerFaceColor', 'black', 'MarkerSize', 5);
end

if (n>100)
    %figure(2)
    nb=60; % no. of bins
    ledge=0;
    redge=T;
    dlr=(redge-ledge)/nb;
    edges=[ledge:dlr:redge];
    centers=edges+0.5*dlr;
    centers=centers(1:nb);
    r=histc(hv,edges);
    r=r(1:nb);
    r=r/(n*dlr);
    plot(centers,r, 'o');
    hold on;
    xc=[0.01:0.01:T];
    plot(xc, tlhtdens(a,b,xc), 'Color',[1 0 0], 'LineWidth', 2);
    legend('histogram', 'density', 'Location', 'northeastoutside');
    hold off;
end
title('Time when B.m. hits a tilted line');