% Set the paths

globals;

% Enable various phases
doTraining = true;
doTesting = true;
doEvaluation = true;

% Start the experiment
if ~exist('Dtest', 'var') || ~exist('Dtraining', 'var')
  disp('Data not loaded, loading ...');
  load([HCONDATA 'sun09_objectCategories.mat']);
  load([HCONDATA 'sun09_groundTruth.mat']);
end
primaryCat = 'bed';
secondaryCat = 'person';

BASELINE_DIR = [SAVE_DIR 'baseline/' primaryCat '/'];
if ~exist(BASELINE_DIR, 'dir')
  mkdir(BASELINE_DIR);
end

%%
disp('Making selection for Training');
[wPSTr wPnSTr wnPSTr wnPnSTr] = makeSelection([Dtraining], ...
  primaryCat, secondaryCat, false);

delete([tmpdir '*']);
delete([cachedir '*']);

trainSetPosAB = [wPSTr wPnSTr];
trainSetNegAB = [wnPSTr wnPnSTr];

fprintf('All Table Train set Pos %d\n', length(trainSetPosAB));
fprintf('All Table Train Set Neg %d\n', length(trainSetNegAB));

disp('Converting the data...');
[trainSetPosAB trainSetNegAB] = convertDataSun09ToPedro(primaryCat, ...
  trainSetPosAB, trainSetNegAB, true);

disp('Starting the training');
tic;
MODEL_BASE = pedro4TrainBaseline(primaryCat, 3, trainSetPosAB, ...
  trainSetNegAB(1:2000));
toc;
saveSuffix = 'NOPART';
save([BASELINE_DIR sprintf('MODEL_BASE_%s_%s', saveSuffix, primaryCat)],...
  'MODEL_BASE');

% Clear all the training related data to free up memory.
clear wPSTr wPnSTr wnPSTr wnPnSTr;

%%
%Do the testing.
if doTesting
  disp('Making selection for Testing');
  [wPSTe wPnSTe wnPSTe wnPnSTe] = makeSelection([Dtest], ...
    primaryCat, secondaryCat, false);
  testSetPos = [wPSTe wPnSTe];
  testSetNeg = [wnPSTe wnPnSTe];
  all = [testSetPos testSetNeg(1:200)];
  tic;
  [boxes1Base, boxes2Base] = pedro4Test(MODEL_BASE, all);
  save([BASELINE_DIR 'BOXES_BASE_P1_' saveSuffix], 'boxes1Base', ...
    'boxes2Base');
  toc;
end


if doEvaluation
  DdetectorBoxesBase = myDetectors2LMstruct(all, boxes1Base, primaryCat);

  [recall2, precision2, DdetectorDum2, threholds2, score2, correct2, ap2] = ...
    LMrecallPrecision(all, DdetectorBoxesBase, primaryCat, 'nomisses');

  fig9 = figure(9); clf;
  hold on;
  title('Recall Precision');
  plot(recall2, precision2, 'r');
  legend('Baseline');
  hold off;
  saveas(fig9, [BASELINE_DIR saveSuffix '_pr_this_exp.jpg'], 'jpg');
end

%%

visualizeDetections(boxes1Base, all ,[BASELINE_DIR 'imgs/']);

%% Combine


