% hdrGenBacklightMap
%
% Constructs low-resolution map of LED drive vector-> backlight luminance image.
% to use in convex optimization.  Calls hdrSimulate to do most of the hard
% work.  Writes a file called 'backlightMap.mat' with the results.
%
% Runtime is quite a few minutes.
%
% Usage:
%
%   hdrGenBacklightMap(OPTIONS)
%
% Where OPTIONS is a list of option name/value pairs, where the name is one
% of the following:
%
% dev_dir: Directory to use for reading in display device characteristics.
%     Defaults to 'disp14'
% any other option: Passed onward to hdrSimulate to allow for changing LED PSFs
%     or other display parameters. See help hdrSimulate for available
%     options.

function hdrGenBacklightMap(varargin)
    
% Constants
n_leds = 759;
scaled_size =[46 33]; % Size of backlight array if it were filled in to become rectangular
resdir = 'disp14';

% Process arguments
argcount = 0;
for i=1:length(varargin)/2
   argname = lower(varargin{i*2-1});
   value = varargin{i*2};
   switch argname
       case 'dev_dir' % Device parameter directory
           if ( ~exist(value,'dir') )
               disp(sprintf('%s : no such directory',value))
               return
           end
           resdir = value;
       otherwise
           simargs{argcount+1} = argname;
           simargs{argcount+2} = value;
           argcount = argcount + 2;
   end
end

% Load LED mapping 
ledord = load([resdir '/ledord.dat']);

% Initialize images/matrix
white_image = uint8(ones(1024,1280,3) * 255);
backlightMap = zeros(scaled_size(1)*scaled_size(2),n_leds);

disp('Generating mapping matrix');

% Loop through all LEDs
for i=1:n_leds
    if mod(i,5) == 0
        disp(sprintf('Led: %d',i))
    end
    % Turn off other LEDs
    white_image(2,2+ledord,1) = 0;
    % Turn on current LED
    white_image(2,2+ledord(i),1) = 255;
    % Simulate result
    if ~exist('simargs','var')
        single_led_image = hdrSimulate(white_image);  % Default options
    else
        single_led_image = hdrSimulate(white_image,simargs{:}); % Extra options
    end
    % Resize to lower size
    scaled_image = imresize(single_led_image(:,:,1), scaled_size, 'bicubic');
    % And vectorize into matrix
    backlightMap(:,i) = scaled_image(:);
end

% Save matrix
save 'backlightMap.mat' backlightMap

end
