function [Result, Result2] = RGB2CFA(Img_RGB)
%[Result, Result2] = RGB2CFA(Img_RGB): Transform the RGB image to CFA-based image (RGGB sensor array)
%Img_RGB: DATA TYPE: M by N by 3 RGB image 
%Result : DATA TYPE: M by N array 
%   Result stores only R data at odd pixels in odd lines, 
%   B data at even pixels in even lines, and the rest pixels are filled in G
%   data.
%Result2: DATA TYPE: M by N by 3 array
%   Result2 stores the sampled RGB in different channels.

Img_size = size(Img_RGB(:,:,1) );
Img_RGB = double(Img_RGB);
%R, G, B mask generation
tmp_size = ceil( Img_size/2 );
tmp = upsample(upsample( ones(tmp_size),2)',2)';
R_Mask = tmp(1:Img_size(1), 1:Img_size(2) );
tmp = upsample(upsample( ones(tmp_size),2,1)',2,1)';
B_Mask = tmp(1:Img_size(1), 1:Img_size(2) );
G_Mask = ones(Img_size) - R_Mask - B_Mask;

Result = uint8( double(Img_RGB(:,:,1)) .*R_Mask + double(Img_RGB(:,:,2)) .*G_Mask + double(Img_RGB(:,:,3)) .*B_Mask );

Result2 = zeros(Img_size(1),Img_size(2),3);
Result2(:,:,1) = uint8( double(Img_RGB(:,:,1)) .*R_Mask );
Result2(:,:,2) = uint8( double(Img_RGB(:,:,2)) .*G_Mask );
Result2(:,:,3) = uint8( double(Img_RGB(:,:,3)) .*B_Mask );
Result2 = uint8(Result2);