function warpDetectPresenceScript(instanceId, procDir, outputDir)
try
globals;

% Initialize instance some variables
rand('twister', instanceId);
pause(rand(1,1) * 10);

mode = 'Train'; %'Test'; % 'Train'
if ~exist('procDir', 'var')
%   procDir = [CONFIG.processingDir 'pascalClustersCover/diningtable/train/4/'];
%   procDir = [CONFIG.processingDir ...
%     'pascalClustersUnsup/div2/train/assimilated/'];
%   procDir = [CONFIG.processingDir ...
%     '/pascalProcessingUnSupAll/div2/retrain/12497/'];
%   outputDir = [procDir 'detectionResultsTest/'];
  procDir = [CONFIG.processingDir ...
    'pascalClustersUnsupO0p7Alt/div2/train/assimilated/'];
  outputDir = [procDir 'detectionResultsTest/'];
end

if ~exist(outputDir, 'dir')
  mkdir(outputDir);
end
posOutputDir = [outputDir 'pos/'];
if ~exist(posOutputDir, 'dir')
  mkdir(posOutputDir);
end
negOutputDir = [outputDir 'neg/'];
if ~exist(negOutputDir, 'dir')
  mkdir(negOutputDir);
end

% Load processing data
fprintf('Loading detector data ...  \n');
load([procDir 'detectors_MINED.mat'], 'detectors');
% load([procDir 'LOG_RES_DET_LAT.mat'], 'detectors');
if fileExists([procDir 'ALL_DATA.mat'])
  load([procDir 'ALL_DATA.mat']);
elseif fileExists([procDir 'SEL_CLUSTS.mat'])
  load([procDir 'SEL_CLUSTS.mat']);
else
end

fprintf('Done\n');

[posData, negData, allPosData, allNegData] = getDataToProcess(mode, ...
  procDir);

% Initialize the detection parameters.
detectionParams = getDetectionParams(detectors.params);

% Start processing the images
outSuffix = '_res';
posFiles = processImages(allPosData, posData, detectors, ...
  posOutputDir, outSuffix, detectors.params.homeImgs.pos, detectionParams);
negFiles = processImages(allNegData, negData, detectors, ...
  negOutputDir, outSuffix, detectors.params.homeImgs.neg, detectionParams);

saveDataInfo(posData, negData, outputDir)
disp('Done Processing Everything');
% Wait for others to get done.
while ~waitTillExists(posFiles)
end
while ~waitTillExists(negFiles)
end
collateData(instanceId, outputDir, selectedClusters);
catch exception
displayStackTrace(exception);
end
end

function collateData(instanceId, outputDir, selectedClusters)
flagFile = [outputDir 'all_detections.flag'];
if ~exist(flagFile, 'file') && instanceId == 1
  collateDetectionResults(outputDir, selectedClusters)
  createFlagFile(flagFile);
end
waitTillExists({flagFile});
end

function fileNames = processImages(data, imageIds, detectors, ...
  outputDir, outSuffix, imgHome, detectionParams)
randInds = randperm(length(imageIds));
fileNames = cell(size(imageIds));
for i = 1 : length(randInds)
  ind = randInds(i);
  imgId = imageIds(ind);
  fileId = sprintf('%d%s.mat', imgId, outSuffix);
  fileNames{ind} = [outputDir fileId];
  if isStillUnprocessed(fileId, outputDir)
    fprintf('Processing image %d\n', imgId);
    detResults = detectors.detectPresenceInImg(data(imgId), imgHome, ...
      true, detectionParams);
    
    save(fileNames{ind}, 'detResults');
    doneProcessing(fileId, outputDir);
    fprintf('Done processing image %d\n', imgId);
  end
end
end

function detectionParams = getDetectionParams(params)
detectionParams = struct( ...
  'selectTopN', false, ...
  'useDecisionThresh', true, ...
  'overlap', 1.1, ...
  'fixedDecisionThresh', -1);

%'overlap', params.overlapThreshold, ...
end

function saveDataInfo(testSetPos, testSetNeg, outputDir)
fileNameBase = 'trainingData.mat';
if isStillUnprocessed(fileNameBase, outputDir)
  trainingData.pos = testSetPos;
  trainingData.neg = testSetNeg;
  save([outputDir fileNameBase], 'trainingData');
  doneProcessing(fileNameBase, outputDir);
end
end


