%% Gaussain Fitting for single LED Point Spectral Function
% The output x of this script is used in brsGetBacklightImage2 as PSF
% curve fitting

% Define the LED used in the Measurement
Test_LED = zeros(31*5,89*3); 
% intermediate space used for filtering, because filtering [1080,1920] 
% matrix takes too long. Greg Ward's algorithm uses this intermediate size as well.
% We do all the filtering in this intermediate space.
Test_LED(16*5,44*3) = 1; % position of the measured single LED 
% coresponds to position(16,22) in brsPutLed Function. 
% To convert btw two coordinates you need to know what the heaxagonal grid looks like.
backlight = Test_LED;
%figure;imagesc(backlight);colormap('gray');

gaussrad = [4 6 8 12 16 32 64 128];
% Test Gaussians to fit PSF.
gausswidth = min(89*3,10*gaussrad);
for idx = 1:length(gaussrad)
    % t_start = clock;
    backlight_gauss(:,:,idx) = imfilter(backlight,fspecial('gaussian',gausswidth(idx),gaussrad(idx)),'replicate');
    G(:,idx) = reshape(backlight_gauss(:,:,idx),size(backlight,1)*size(backlight,2),1);
    % figure;imagesc(backlight_gauss(:,:,idx));colormap('gray');
    % t_end = clock;
    % disp(sprintf('Encoding Done succesfully - elapsed time: %.2f seconds',etime(t_end,t_start)));
end
%backlight = imresize(Test_LED,dstsiz,'bicubic');
%% Curve Fitting
% load the measured Point Spread Function data.
load hdr-Combined2;
image = hdrImage(54:426,55:717,:);
Ideal_PSF = imresize(image(:,:,1)+image(:,:,2)+image(:,:,3),size(backlight),'bicubic');
d = Ideal_PSF(:)./max(Ideal_PSF(:));
C = G;
x = C\d;
RESNORM = norm(d-C*x)^2
% returns the vector X that minimizes NORM(d-C*X) subject to X >= 0.
% x can be used as weights to test gaussians in brsGetBacklightImage2
% RESNORM can be a indicator of how close the curve fitting is.
% figure;imagesc(Ideal_PSF);colormap('gray');
% figure;imagesc(reshape(C*x,31*5,89*3));colormap('gray');

%% Measurements Related...
% n = 10 pixels/grid
% V : 29*n/100 pixels/cell; 504cells = 504*29*n/100=1461 pixels total =>
% H : 29*n/100 pixels/cell; 760cells = 760*29*n/100=2204 pixels total => 
% mid point = [240,386] => Display = [54:426 55:717]

