function rgbdscenelabeling(SEQ)
% Run detection and generate probabilistic score maps

rootdir = [pwd '/'];
addpath(genpath([rootdir '../']));

SEQ = sscanf(SEQ,'%d');

FRAME_SKIP = 1;

DATADIR = '/projects/robomap3/nobackup/kevinlai/rgbddata/';
TESTDIR = [DATADIR 'test/'];
TRUTHDIR = [DATADIR 'groundtruth/'];

CATEGORIES = {'bowl', 'cap', 'cereal_box', 'coffee_mug', 'soda_can'};

THRESHOLD = -0.6;

load([rootdir 'categorySizes.mat']);
cnt=1;
for cat=1:length(CATEGORIES)
   testcategory = CATEGORIES{cat};
   try
      load([rootdir 'model/' testcategory '_' 'joint']);
   catch
      continue;
   end
   model.sfactor = 1.1;
   model.threshold = THRESHOLD;
   model.topN = 3;
   modelcell{cnt} = model;
   cnt=cnt+1;
end

% set image directory
[imdir, labeldir] = gettestdir(TESTDIR,TRUTHDIR);
index = SEQ;
for i = 1:length(index)
    subimdir{i} = imdir{index(i)};
    sublabeldir{i} = labeldir{index(i)};
end


it = 0;
tic;
for i = 1:length(subimdir)
    % get the sequence name
    depthname = dir([subimdir{i} '*_depth.png']);
    load(sublabeldir{i});
    nums = zeros(1,length(depthname));
    for j=1:length(depthname)
       parts = regexp(depthname(j).name,'_','split');
       nums(j) = str2num(parts{end-1});
    end
    [Y I] = sort(nums);
    depthname = depthname(I);

    for j = 1:FRAME_SKIP:length(depthname)
        depthname(j).name
        % load image and depth
        impath = [subimdir{i} depthname(j).name(1:end-10) '.png'];
        depthpath = [subimdir{i} depthname(j).name];
        im = imread(impath);
        depth = imread(depthpath);
        % get ground truth bounding boxes
        index = find(depthname(j).name  == '_');
        frame = str2num(depthname(j).name((index(end-1)+1):(index(end)-1)));
        bboxtrue{j} = bboxes{frame};

        % run detector
        [score, pfea, modelcell] = rgbddetect(im, depth, modelcell);
        bb = [];
        for m=1:length(modelcell)
           scoreMaps = rgbdbbox_scenelabeling({score{m,:}}, pfea, {modelcell{m}});
           pixScores = zeros(size(scoreMaps(1).pixScores,1),size(scoreMaps(1).pixScores,2),length(scoreMaps));
           for b=1:length(scoreMaps)
              pixScores(:,:,b) = scoreMaps(b).pixScores;
           end
           scoreMaps(1).pixScores = max(pixScores,[],3);
           scoreMaps(1).pixScores = 1./(1+exp(-3*(scoreMaps(1).pixScores-THRESHOLD)));
           
           boxes = rgbdbbox({score{m,:}}, pfea, {modelcell{m}});
           for b=1:length(boxes)
              box = boxes(b);

              depthCrop = double(depth(box.top:box.bottom,box.left:box.right));
              g = round(modelcell{m}.grid/box.scale/2);
              centerDepth = double(depth(box.cheight-g:box.cheight+g,box.cwidth-g:box.cwidth+g));
              centerDepth = median(centerDepth(:));
              normDepth = centerDepth/box.scale;
              diff = abs(normDepth - mean(normDepths{m}));
              if diff > 700
                 bscore = 1e-5;
              else
                 bscore = 1./(1+exp(-1*(box.score-THRESHOLD)));
              end

              pixScores = bscore*exp(-0.00005*(depthCrop-centerDepth).^2);
              scoreMaps(1).pixScores(box.top:box.bottom,box.left:box.right) = max(scoreMaps(1).pixScores(box.top:box.bottom,box.left:box.right), pixScores);
           end

           bb = [bb scoreMaps(1)];
        end
        bbox{j} = bb;

%       figure(1); imshow(im); figure(2); imagesc(depth);
%       for b=1:length(bb) 
%          figure(b+2); imshow(bb(b).pixScores);
%       end
%       disp('paused'); pause;
        %bbox{j} = rgbdbboxinstance(score, pfea, modelcell);
        % print results
%        rgbdbbplot(im, bbox{j}); 
%	disp(sprintf('Frame %d',j));
%	print('-dpng',[rootdir sprintf('output/frame_%d.png',j)]);
%        pause; 
%        if mod(j,10) == 1
%           disp(['Current iteration is ' num2str(j)]);
%        end
    end
end
disp(['Running time is ' num2str(toc)]);

% averaged precision
if model.instance == 0 
   categorytag = 1;
else
   categorytag = 0;
end
[rec, prec, ap, sc] = rgbdaprecision(bboxtrue,bbox,categorytag);
%figure(1); clf;
%rgbdprplot(rec, prec, 'r');

mkdir([rootdir 'results_det']);
if model.imagetag == 1 & model.depthtag == 1
   savedir = [rootdir sprintf('/results_det/all_category_joint_%d.mat',SEQ)];
elseif model.imagetag == 1 & model.depthtag == 0
   savedir = [rootdir sprintf('/results_det/all_category_image_%d.mat',SEQ)];
elseif model.imagetag == 0 & model.depthtag == 1
   savedir = [rootdir sprintf('/results_det/all_category_depth_%d.mat',SEQ)];
end

save(savedir, 'bboxtrue', 'bbox', 'ap', 'rec', 'prec','-v7.3');


