function gtLabelSet = gt_labeling(imageSet, gt_label_dir, pars)

% parameter parsing
gridSpacing = pars.gridSpacing;
patchSizes = pars.patchSizes;
maxImSize = pars.maxImSize;

gtLabelSet = imageSet;
gtLabelSet.path = {};
if ~isdir(gt_label_dir)
    mkdir(gt_label_dir);
end

for ii = 1:imageSet.imnum,
    tic;
    
    impath = imageSet.imgpath{ii};
    [pathstr, name, ext] = fileparts(impath);
    fprintf('Processing the image %s...', name);
    
    fpath = fullfile(gt_label_dir, [name, '.mat']);
    gtLabelSet.path = [gtLabelSet.path; fpath];
    
    if exist(fpath,'file')
        fprintf('Skipped.\n');
        continue;
    end
    % read and rescale ground truth
    gtpath = imageSet.gtpath{ii};
    if strcmp(gtpath,' ')
        I = imread(impath);
        [im_h, im_w, im_c] = size(I);
        GT = ones(im_h, im_w);
    else
        GT = imread(gtpath);
        [im_h, im_w] = size(GT);
        if max(im_h, im_w) > maxImSize,
            GT = imresize(GT, maxImSize/max(im_h, im_w), 'bicubic');
        end;
        GT = round(GT/127);
        GT(GT>0) = 1;
    end

    gtLabel.GT = GT;
    gtLabel.x = [];
    gtLabel.y = [];
    gtLabel.gt = [];
    for p = 1 : length(patchSizes)
        patchSize = patchSizes(p);
        
        % make grid sampling SIFT descriptors
        remX = mod(im_w-patchSize,gridSpacing);
        offsetX = floor(remX/2)+1;
        remY = mod(im_h-patchSize,gridSpacing);
        offsetY = floor(remY/2)+1;

        [gridX,gridY] = meshgrid(offsetX:gridSpacing:im_w-patchSize+1, offsetY:gridSpacing:im_h-patchSize+1);
        
        % make ground truth on grid
        gt = zeros(size(gridX));
        for y = 1 : size(gridX, 1)
            for x = 1 : size(gridX, 2)
                label = GT(gridY(y,x):gridY(y,x)+patchSize-1, gridX(y,x):gridX(y,x)+patchSize-1);
                if find(label==0)
                    gt(y, x) = 1;
                else
                    gt(y, x) = -1;
                end
            end
        end
        gtLabel.gt = [gtLabel.gt; gt(:)];
        x = gridX(:) + patchSize/2 - 0.5;
        y = gridY(:) + patchSize/2 - 0.5;
        gtLabel.x = [gtLabel.x;x];
        gtLabel.y = [gtLabel.y;y];

    end

    gtLabel.width = im_w;
    gtLabel.height = im_h;


    save(fpath, 'gtLabel');

    fprintf(' in %f seconds.\n', toc);
end;

disp('Done!');
