function [root,Iteration] = bisect2(f,a,b,imax,tol,n)
% This Function uses the bisection method to root solve equation 'f'...
% for multiple roots bewteen 'a' and 'b' to a tolerence of 'tol'...
% with max iterations 'imax'. N determines the amount of guesses.
% Input: f function to be evaluated
% a,b interval limits
% imax iteration maximum
% tol convergence criterion
% n is number of guesses between a and b 
% Output: root position of the root
% initialise parameters, i.e.

x = linspace(a,b,n);
yofF = 100.*exp(-x)-5.*sin((pi.*x)./2);
for i = 1:n-1
    y1 = yofF(1,i);
    y2 = yofF(1,i+1);
    Rootest(1,i) =  yofF(1,i).*yofF(1,i+1);
end

RootTest = logical(Rootest<0);
RootTesta = find(RootTest>0);
RootTestb = RootTesta(1,:)+1;

    a = x(1,RootTesta(1,:));
    b = x(1,RootTestb(1,:));

sizeOfa = size(a); 
% Create a for loop here for each a and b value
for i = 1:sizeOfa(1,2)

x1=a(1,i);           % x1 is lower guess for x
x3=b(1,i);           % x3 is upper guess for x
% x2 is midpoint for x
f1=feval(f,x1); 
f3=feval(f,x3);
if f1*f3>0
% CHECK: verify that there is indeed a root in the interval [x1(a) x3(b)].
error('No root in the specified interval')
end

diff = inf;
counter = 0;
while diff>tol && counter<imax
   f1 = feval(f,x1);
   f3 = feval(f,x3);
    
    x2 = (x3+x1)/2;
    f2 = feval(f,x2);

    % fprintf('ITERATION %i \r',counter)
    % fprintf('Lower guess = %.7f \r',x1)
    % fprintf('Upper guess = %.7f \r',x3)
    % fprintf('Mid-point = %.7f \r \r',x2)

    if f1*f2<0
        % Root is in left half, so
        f3=f2;
        x3=x2;
      else
        % Root is in right half, so
        f1=f2;
        x1=x2;
    end
    diff = norm(x3-x1);
    counter = counter+1;
end
    Iteration(1,i) = counter;
    root(1,i)= x2;
    fprintf('ITERATION %i \r',Iteration(1,i))
    fprintf('Root Estimate (6 d.p.) = %.6f \r\r',root(1,i))
end
end
