globals;
addpath(genpath(CONFIG.detectorCode));
clusterSource = CONFIG.processedSource;
detectionTarget = [CONFIG.processedSource '/detections/'];

%datasets: 'TrainTrainSplit', 'TrainValSplit', 'TestSplit'

if(~exist(detectionTarget))
    mkdir(detectionTarget);
end

myRandomize;

%load detectors
detectors = loadDetectors([clusterSource '/detectors/detectors.mat']);
target = [detectionTarget '/' ];

if(~exist(target))
    mkdir(target);
end

imageSources = {[CONFIG.trainTrain '/']};
resultTargets = {[target '/train/']};

for targetI=1:numel(resultTargets)
    if ~exist(resultTargets{targetI})
        mkdir(resultTargets{targetI});
    end 
end

%the base path
sourceBases = {};
%the filename
sources = {};
%the target mat file
results = {};

for sourceI=1:numel(imageSources)
    images = dir([imageSources{sourceI} '/*.jpg']);
    for imageI=1:numel(images)
        sourceBases = [sourceBases, imageSources{sourceI}];
        sources = [sources, images(imageI).name];
        results = [results, [resultTargets{sourceI} '/' images(imageI).name '.mat']]; 
    end
end

detectionParams = struct('selectTopN', false, 'useDecisionThresh', true, 'overlap', 0.4, 'fixedDecisionThresh', -1.1);

imageOrder = randperm(numel(sources));
parfor ii=1:numel(sources)
    i = imageOrder(ii);
    fprintf('Image %d (%d): ', ii, i);
    if (exist(results{i})) || isLocked([results{i} '.lock'])
        fprintf('skipping\n'); 
        continue;
    end

    fprintf('running\n');

    %load the image in the format the detectors want
    imageStruct = loadImageStruct(sourceBases{i}, sources{i});
    detections = detectors.detectPresenceInImg(imageStruct, sourceBases{i}, true, detectionParams);
    saveToMat(results{i},'detections',detections);

    unlock([results{i} '.lock']);

end

