function [t]=first_return(delta,tau,plot_flag)
% first_return.m
%
% USAGE: [t] = first_return(delta,tau,plot_flag)
%
% The code will run a random walk on a one-dimensional lattice (lattice spacing: delta) taking
% one step in time tau. The code returns the time that the walker first
% returns to the origin

% set default value for plot_flag to be 0 => no plot is created
if nargin <3, plot_flag = 0; end
if plot_flag
    figure;
    scatter(0,0,'bo');
    hold on;
    drawnow
end

t = 0;
h = 0;
kill_switch = 0; % this variable turns from 0 to 1 at the first return

while kill_switch==0
    Random_number=rand(1);% generate a random number between zero and one
    
    if Random_number>.5
        h=h+delta; % when the number is greater than .5 take a step up
        t=t+tau; % record that time passed
    elseif Random_number<.5
        h=h-delta; % when the number is less than .5 take a step down 
        t=t+tau; % record that time passed  
    end
    
    if plot_flag
        scatter(t,h,'bo');
        hold on;
        drawnow
    end
    
    if h==0;% h==0 % stop the while loop when the walker returns
        kill_switch=1;
    end
    
end
