%% contrib.cal equivalent - diagonal matrix solve
function hexagonal_backlight = brsGetCrosstalk2(ideal_backlight)
% Adjusts LED drive values to account for crosstalk from neighboring LEDs
% Use pseudo inverse an dleast squares to find the optimal LED values that
% match the ideal_LED image
    load hdrCalibrationData\LED_response_matrix % Load precaculated LED_response Matrix
    %figure;imagesc(reshape(LED_response(:,100),31,89));colormap('gray');
    method = 4; %1-for Least Squares 2-MATLAB lsqnonneg 3-CVX

    box_filter_size = [20 20];
    intermediate_siz = [31*2 89*2];
    ideal_backlight = imfilter(ideal_backlight,fspecial('average',box_filter_size),'replicate'); 
    ideal_backlight = imresize(ideal_backlight,intermediate_siz,'bilinear',0);
%    ideal_backlight = imfilter(ideal_backlight,fspecial('gaussian',15,gaussian_radius),'replicate'); 
%    ideal_backlight =
%    imresize(ideal_backlight,backlight_siz,'bilinear',0);

    d = ideal_backlight(:);
    if (method == 1)
        C = LED_response;
        % t_start = clock;
        x = max(C\d,0); % using Least-Squares will result in negative solutions.
        % t_end = clock;
        % disp(sprintf('Done succesfully - elapsed time: %.2f seconds',etime(t_end,t_start)));
    elseif (method == 2)
        C = LED_response;
        % t_start = clock;
        [x RESNORM] = lsqnonneg(C,d);
        % returns the vector X that minimizes NORM(d-C*X) subject to X >= 0.
        % x is the hexagonal LED value
        % RESNORM can be a indicator of how close we are
        % RESNORM
        % t_end = clock;
        % disp(sprintf('Done succesfully - elapsed time: %.2f seconds',etime(t_end,t_start)));
        % did not finish in 48 hours.
    elseif (method == 3)
        LED_response(find(LED_response<0.01)) = 0;
        C = sparse(LED_response);
        % t_start2 = clock;
        cvx_begin
            variable x(1380,1)
            minimize (norm(d-C*x,2))
            subject to
            x>=zeros(1380,1);
        cvx_end
        % t_end2 = clock;
        % disp(sprintf('Done succesfully - elapsed time: %.2f seconds',etime(t_end2,t_start2)));
        save x_matrix_cvx x
        % CVX takes about 597.36 seconds.
    elseif (method == 4)
        load x_matrix_cvx_2_2;
    end
    hexagonal_backlight = zeros(31,89);
    idx = 1;
    for m = 1:31
        for n = 1:44+2*(m/2-floor(m/2))
            col = 2*n-2*(m/2-floor(m/2));
            hexagonal_backlight(m,col) = x(idx);
            idx = idx+1;
        end
    end
    %figure;imagesc(hexagonal_backlight);colormap('gray');
end
