function [ target ] = recoverFence(imOriginal, maskOriginal, imMasked, mask, expName, outFolder )
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here

[height width] = size(mask);
level = floor(log2(min(height, width)));
pyramidIM = cell(1, level);
pyramidMSK = cell(1, level);

flag=1; %To check the marked region presence
count = 0; %Counts the levels

newFName = strcat(int2str(count),'reduce', expName,'.bmp' );
imwrite(imMasked, newFName);
pyramidIM{count+1} = imMasked;
pyramidMSK{count+1} = mask;
figure; imshow(imMasked);
count = count+1;


for i=1:level
    if(flag==1)
        [rim] = reduce(imMasked);
        [mask] = reduce(mask);
        
        newFName = strcat(outFolder,'/',int2str(i),'reduce',expName, '.bmp');
        imwrite(rim ,newFName);
        figure, imshow(rim);
        % check for balck
        indx = find(mask == 1);
        if ~size(indx) 
            flag = 0;
        elseif size(mask, 1) <= 300
            flag = 0;
            [rim,~,~,~,~,~] = inpaint7(rim, rim, [0 0 0]);
            
            
            rim = uint8(rim);
            newFName = strcat(outFolder,'/',int2str(i),'expand',expName, '.bmp');
            
            imwrite(rim ,newFName);
            figure, imshow(rim);
            
        end
        %         flag = chkBlack(rim);
        count = count+1;
        pyramidIM{count} = rim;
        pyramidMSK{count} = mask;
        imMasked = rim;
        clear rim;
    else
        break;
    end
end

pyramidIM = pyramidIM(~cellfun(@isempty, pyramidIM));
pyramidMSK = pyramidMSK(~cellfun(@isempty, pyramidMSK));
% display(count);

% Upsampling
for i=count:-1:2
    im = pyramidIM{i};
    
    %             exp = uint8(expandd2(im));
    %         exp = imresize(im, 2, 'bilinear');
    exp = myExpand2D(im);
    
    figure, imshow(exp); title('expanded');
    mask = pyramidMSK{i-1};
    target = pyramidIM{i-1};
    [x,y] = find(mask==1);
    for j=1:size(x)
        if mask(x(j), y(j))
            target(x(j), y(j),1) = exp(x(j), y(j),1);
            target(x(j), y(j),2) = exp(x(j), y(j),2);
            target(x(j), y(j),3) = exp(x(j), y(j),3);
        end
    end
    %     target = cv.GaussianBlur(target, 'KSize', [3,3]);
    
    figure, imshow(uint8(target));
    newFName = strcat(outFolder,'/',int2str(i-2),'expand',expName, '.bmp');
    imwrite(target ,newFName);
    
    pyramidIM{i-1} = target;
    if i ~= 2
        clear target im exp mask
    end
end

% target = cv.GaussianBlur(target, 'KSize', [3,3]);

end

