function outDeblurredImage = Deblurring(inImage1, inImage2, inBlurMap, inKernel1, inKernel2, inSigma);

% Given defocus images, aperture patterns, and depth map
% Compute an all-focused image

% written by Changyin Zhou @ Columbia U, September 2009

inKernelSize = size(inKernel1, 1);
throughout1 = sum(inKernel1(:));
throughout2 = sum(inKernel2(:));

backup = inImage1;
inImage1 = fft2(inImage1);
inImage2 = fft2(inImage2);

%Prepare the prior matrix
global AStar;
[hei, wid] = size(inImage1);
lambda = (inSigma^2*hei*wid)./AStar+0.0001;

outDeblurredImage = zeros(hei, wid);
count = 0;

while(1) %Try all possible depths
    blurSZ = max(inBlurMap(:));
    select = inBlurMap==blurSZ;
    
    if blurSZ==-999
        break;
    end;  
    
    if blurSZ ==0
        outDeblurredImage(select) = backup(select)/throughout1;
        inBlurMap(select) = -999;
        continue;
    end;
    inBlurMap(select) = -999;

    [kernel1, kernel2] = eScaleKernel(hei, wid, inKernel1, inKernel2, blurSZ, throughout1, throughout2);
    
    %This one-line code is the Generalized Weiner Deconvolution Algorithm
    temp = abs(ifft2((inImage1.*conj(kernel1)+inImage2.*conj(kernel2))./(kernel1.*conj(kernel1)+kernel2.*conj(kernel2)+lambda))); 
    
    %Merge the defocused peices
    outDeblurredImage(select) = temp(select); 
    count = count +1;
end;
