function sample_neg_patch(patch_size,num_patch,overwrite)
% sample_neg_patch - Collect random patches.

folder = '../image/neg';
if nargin < 1
    patch_size = [120 120];
end
if nargin < 2
    num_patch = 200;
end
if nargin < 3
    overwrite = true;
end

% disp(sprintf('patch size: %d by %d',patch_size(1), patch_size(2)));
destFolder = sprintf('../image/neg_%d_%d',patch_size(1),patch_size(2));

if exist(destFolder,'dir')
    if ~overwrite
        return
    end
else
    mkdir(destFolder);
end

JPGs = dir([folder '/*.jpg']);
n = length(JPGs);
I = cell(n,1);
for i = 1:n
    I{i} = imread([folder '/' JPGs(i).name]);
end

iToss = 1;
while iToss <= num_patch
    % randomly select a scale
    u = rand;
    if u < 0.8
        logscale = 0;
    elseif u < 0.2 * 0.8
        logscale = 1;
    else
        logscale = 2;
    end

    % randomly select an image
    u = rand;
    imageInd = ceil(u*n);
    
    % rescale the image
    if logscale~=0
        im = imresize(I{imageInd},exp(-logscale),'nearest');
    else
        im = I{imageInd};
    end
    
    % possible rejection
    if size(im,1) <= patch_size(1) || size(im,2) <= patch_size(2)
        continue;
    end
    
    % randomly select a position
    u = rand;
    validHeight = size(im,1) - patch_size(1) + 1;
    validWidth = size(im,2) - patch_size(2) + 1;
    positionInd = ceil( u * validHeight * validWidth );
    col = ceil( positionInd / validHeight );
    row = positionInd - (col-1) * validHeight;
    
    % output the random patch
    patch = im(row+(0:patch_size(1)-1),col+(0:patch_size(2)-1),:);
    imwrite(patch,[destFolder '/' num2str(iToss) '_' JPGs(imageInd).name],'jpg');
    
    iToss = iToss + 1;
end


