% new version using backtracking line search
function [x_sol,num_iters_taken,tElapsed] = smooth_steepest_descent(A,b,tau,x0,TOL,maxiters) 

tic;
m = size(A,1);
n = size(A,2);
At = A';

num_iters_taken = 0;
xn = x0;
xn1 = x0;
quit_loop = 0;

% note we use fixed sigma but we should probably use sequence of decreasing sigmas..
sigmas = linspace(2,0.01,maxiters);

fprintf('in smooth_steepest_descent, starting loop..\n');
fprintf('maxiters = %d, tau = %f\n', maxiters, tau);
for i=1:maxiters
    if quit_loop ~= 1
        fprintf('doing smooth steepest descent2 iter %d of %d with tau = %f\n', i, maxiters, tau);

        num_iters_taken = i;

        % compute delta_x at fixed sigma
        gradxn = gradF(A,b,tau,xn);
        p = - gradxn;

        % compute mu via line search method
        fprintf('line searching..\n');
        mu = backtracking_line_search(A,b,tau,xn,p);
        fprintf('done with mu = %f\n', mu);

        xn1 = xn;
        xn = xn + mu*p;

        % remove small components
        xnabssorted = sort(abs(xn),'descend');
        xnabssorted = xnabssorted(find(xnabssorted>0));
        threshold = xnabssorted(round(0.07*length(xnabssorted)));
        fprintf('length(xnabssorted) = %d and threshold = %f\n', length(xnabssorted), threshold);
        for j=1:n
            if abs(xn(j)) < threshold
                xn(j) = 0;
            end
        end

        % compute diff between un and un1 and quit if small
        if(i>3 && (100*(norm(xn - xn1)/norm(xn)))<TOL)
            fprintf('reached convergence..\n');
            quit_loop = 1;
        end
    else
        break;
    end
end

% record solution
x_sol = xn;

% record time
tElapsed = toc();

end
