function rgb = nhkIP_4x2_bilinear( bayer, cfaPattern )
%Bilinear demosaic algorithm 
%
%    rgb = Bilinear( bayer, cfaPattern )
%
% Demosaic'ing algorithms estimate missing color information by
% interpolation of the known color information across different color
% planes.  
%
% This routine implements a bilinear algorithm
%
% Copyright ImagEval Consultants, LLC, 2005.


% TODO:  Should check arguments, update programming style
%

[r,c,nPlanes] = size(bayer);

% There are three basic configurations for a color sensor in a 2x2 block.
% The sensor can occupy a single location, a pair of locations in a common row/col,
% or a pair of locations in diagonal positions.  We use the appropriate
% linear interpolation kernel in each of these cases.

% Hiroshi's Question: From where value of nPlanes comes?
% How can I know the value?
% (Just by typing "nPlanes" in the command window?)
% As a result, I could't jump to G channel patter.
% ?I want to understand here.
for ii=1:nPlanes
    thisPlane = bayer(:,:,ii); %? ii = [1 2 3], so thisPlane must be color image?
    l = (cfaPattern == ii); %? if [cfaPattern] equal [1 2 3] return [1 1 1]
    if ( l(1) == 1 & l(4) == 1) | (l(2) == 1 & l(3) == 1)  
        % G channel?
        disp('nhkIP_4x2_bilinear for G channel')
        % Opposite coner positions
        rgb(:,:,ii) = conv2(thisPlane, [0 0 0; 0 1/4 0; 1/4 1 1/4; 0 1/4 0; 0 0 0], 'valid');        
    else  
        disp('nhkIP_4x2_bilinear for B/R channel')
        % Otherwise
        thisPlane   = conv2(thisPlane, [1/3 1/3 1/3] , 'valid');
        rgb(:,:,ii) = conv2(thisPlane, [1/2 1 1 1 1/2]', 'valid');
    end
end

return;

% figure; imagesc(thisPlane); colormap(gray)
% figure; imagesc(rgb(:,:,ii)); colormap(gray)