function [Im , ResIm_OMPonly] = extrapolate(trueIm, Im , Mask, extrap, direction, patchSize)

% Params
param.patchSize = patchSize;
param.noiseSig = 0;
param.errorGoal = 0.15;
param.maxAtoms = 20;
param.nAtoms = 100;
param.IgnoreUnmasked = 1;

% Break image to columns (mask as well)
trueimPatches = im2col(trueIm , param.patchSize , 'sliding');
imPatches = im2col(Im , param.patchSize , 'sliding');
maskPatches = im2col(Mask , param.patchSize , 'sliding');

% Run specialized OMP

% Dictionary training param
param.method = 'KSVD';
param.nAtoms = 100; %64

param.nIterations = 4; 
param.useLessAtoms = [0.1 0.1 0.2 0.2 0.4 0.4 0.7 0.7 1 1 1 1 1 1 1];

% param.initType = 'RandomPatches'; 
param.initType = 'DCT'; 


DCTdict = Extrapolate_Dictionary(trueimPatches, param);

% DCTdict = Build_DCT_Overcomplete_Dictionary(param.nAtoms , param.patchSize);

sizeIm = size(Im);

switch direction
case 1 
    Im=Im(:,1:end-extrap-1);
    Mask=Mask(:,1:end-extrap-1);
case 2 
    Im=Im(1:end-extrap-1,:);
    Mask=Mask(1:end-extrap-1,:);
case 3 
    Im=Im(:,extrap+2:end);
    Mask=Mask(:,extrap+2:end);
case 4 
    Im=Im(extrap+2:end,:);
    Mask=Mask(extrap+2:end,:);
end

%% Loop for iterate
for ii=1:extrap+1

%switch direction of extrapolation 
switch direction
case 1 
    Im(:,end+1)=0;
    Mask(:,end)=1;
    Mask(:,end+1)=0;
case 2 
    Im(end+1,:)=0;
    Mask(end,:)=1;
    Mask(end+1,:)=0;
case 3
    tIm=zeros(size(Im,1),size(Im,2)+1);
    tIm(:,2:end)=Im;
    Im=tIm;
    Mask=ones(size(Im));
    Mask(:,1)=0;    
    Mask = logical(Mask);
case 4
    tIm=zeros(size(Im,1)+1,size(Im,2));
    tIm(2:end,:)=Im;
    Im=tIm;
    Mask=ones(size(Im));
    Mask(1,:)=0;
    Mask = logical(Mask);
end


imPatches = im2col(Im , param.patchSize , 'sliding');
maskPatches = im2col(Mask , param.patchSize , 'sliding');
    
resPatches = OMP_Extrapolate(DCTdict , imPatches , maskPatches, param);
resPatches=min(max(resPatches,0),255);

% Reconstruct image
ResIm_OMPonly = Average_Overlapping_Patches(resPatches, size(Im) , param.patchSize);

% For the case of nonzero noise
ResIm = ResIm_OMPonly;
ResIm(Mask) = Im(Mask);

Im=ResIm;


ii=ii+1;


end

% Finished
return;

