function mainHDR_CFA(filenameIn,typeI)
% function mainHDR_CFA(filename,kind)
% call HDR CFA on filename
% filename: image to be treated
% kind:     type of image (CRW, JPG, HDR)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% -----------------------------------------------------------------------
% HDR CFA Image Rendering (Tone Mapping) 
% Written by David Alleysson and Laurence Meylan
% Copyright (C) 2007 Laboratory of Audiovisual Communications (LCAV), 
% Ecole Polytechnique Federale de Lausanne (EPFL), 
% CH-1015 Lausanne, Switzerland 
% 
% This program is free software; you can redistribute it and/or modify it 
% under the terms of the GNU General Public License as published by the 
% Free Software Foundation; either version 2 of the License, or (at your 
% option) any later version. This software is distributed in the hope that 
% it will be useful, but without any warranty; without even the implied 
% warranty of merchantability or fitness for a particular purpose. 
% See the GNU General Public License for more details 
% (enclosed in the file GPL). 
%
% Latest modifications: January 25, 2007, by Laurence Meylan


close all

% global variable for displaying intermediary results
global DISPLAY
global filename
filename = filenameIn;

% Different option depending on the type of the input image
% read the image in Im
switch (typeI)
    case 'HDR'
        CFA = makeMosaic_hdr(filename);
    case 'JPG'
        CFA = makeMosaic_jpg(filename);
    case 'CRW'
        CFA = double(imread(filename));
        CFA= CFA/max(CFA(:));
    otherwise
        error('MainHDR_CFA, line 23: Wrong input image type');
end

% CFA is a mosaic image that takes value in the range [0 1]

% optional display result
if DISPLAY
    [H W P]=size(CFA);
    I_disp = zeros(size(CFA,1),size(CFA,2),3);
    I_disp(1:2:H,1:2:W,1)=CFA(1:2:H,1:2:W,1);
    I_disp(2:2:H,1:2:W,2)=CFA(2:2:H,1:2:W,1);
    I_disp(1:2:H,2:2:W,2)=CFA(1:2:H,2:2:W,1);
    I_disp(2:2:H,2:2:W,3)=CFA(2:2:H,2:2:W,1);
    imwrite(I_disp.^(1/2.2),[filename '_mosaic_gamma.jpg']);
    imwrite(I_disp,[filename '_mosaic_lin.jpg']);
    max_mosaic_image=max(CFA(:))
    min_mosaic_image=min(CFA(:))
end
    
% call the two non-linearities
Im2=GanglionLocalNL(HoriLocalNL(CFA));

% start demosaicing
% i) get luminance and chrominance
[Lum Chr]=GetLumChr(Im2);

% optional display result
if (DISPLAY)
    maxlum = max(Lum(:))
    minLum = min(Lum(:))
    maxchrom = max(Chr(:))
    minchrom = min(Chr(:))
end

% ii) interpolate chrominance
Chr=InterpChr(Chr);
[H W P]=size(Chr);

% iii) construct RGB image
Im3=reshape([Lum+Chr(:,:,1) Lum+Chr(:,:,2) Lum+Chr(:,:,3)],H,W,3);
% imwrite(Im3,[filename '_new' '.jpg'],'jpg');

% optional display result
if (DISPLAY)
    maxIm3 = max(Im3(:))
    minIm3 = min(Im3(:))
end

% iii) apply histogram clipping and scaling to ensure good black and good
% white values
Im3_clip = histoClip(Im3,0.01,0.995);
imwrite(Im3_clip,[filename '_new_clip' '.jpg'],'jpg');
