function synthIM = SynthTexture(sample, w, s)
% original texture sample

% initialize to a negative number so it's easy to distinguish between
% filled and unfilled
synthIM = -1*ones(s);
synthSize = s;

%% ====================== utility funcitons ========================
function b = isfilled(ijs)
    idxs = sub2ind(synthSize,ijs(:,1),ijs(:,2));
    b = ~(synthIM(idxs)==-1);
end

%% =================================================================

%% pick a random wxw sample from sample and plop it in the middle
seedw = 3;

si = s(1)/2; sj = s(2)/2;
rsrci = 32 - floor(seedw/2); %-floor(w/2);  % floor(rand(1)*(size(sample,1)-seedw))+1;
rsrcj = 4 - floor(seedw/2);  %-floor(w/2); % floor(rand(1)*(size(sample,2)-seedw))+1;
synthIM(si:si+seedw-1,sj:sj+seedw-1) = ...
    sample(rsrci:rsrci+seedw-1,rsrcj:rsrcj+seedw-1);

figure(4);
testshow(synthIM);
figure(1);

%% =================================================================
% precompute a gaussian mask
sigma = w/6.4;
gmask = gauss2d(w,sigma);

% find things to fill
tofill = findEmpty(synthIM,w)

counter = 0; 
%% debugging 
disposed = 0;
%% end debugging
wmiddle = floor(w/2);

while ( length(find(synthIM<0)) > 0) % while we have unfilled pixels
  
  lengthtofill = length(tofill)
  for pt = tofill,
    %% what to do %% 
    pt_i = pt(1);  pt_j = pt(2);
    
    template = getSample(synthIM,pt_i,pt_j,w);
    validmask = makeValidMatrix(synthIM,pt_i,pt_j,w);
    G = validmask .* gmask;
    
    [bestmatch err] = findMatches(template,sample,G);
    synthIM(pt_i + wmiddle, pt_j+wmiddle) = bestmatch(wmiddle+1,wmiddle+1);
    counter = counter+1;
  end
  tofill = findEmpty(synthIM,w);
 end
 
 
%     if (0) % counter > synthSize(1)*synthSize(2) && lengthtofill < 60)
%       figure(2); testshow(template); title('template');
%       figure(3); testshow(bestmatch); title('bestmatch');
%       pause(1);
%     end
% if (lengthtofill == 51)
%   tofill
%   figure(2); testshow(template); title('template');
%   figure(3); testshow(bestmatch); title('bestmatch');
%   bestmatch
%   pt_i
%   pt_j
%   TOFILLIN = [pt_i + wmiddle, pt_j+wmiddle]
%   bestmatchpix = bestmatch(wmiddle+1,wmiddle+1)
%   figure(8); testshow(synthIM); title('synthIM');
%   figure(1);
% end
%% findempty = findEmpty()
%% clean up by filling in unfinished patches
%synthIM(synthIM<=0)=0;
%synthIMsize = size(synthIM)
%synthSize = synthSize
%synthIM = reshape(synthIM,synthSize);

end