addpath(genpath(CONFIG.detectorCode));

clusterSource = CONFIG.processedSource;
normalSource = CONFIG.normalSource;

priorShape = [200,200];

trainSet = CONFIG.trainTrain;
images = dir([trainSet '/*.jpg']);
%sum image
normalSum = zeros(priorShape(1),priorShape(2),3);
%counter
normalNormalizer = zeros(priorShape);

for imageI=1:numel(images)
    fprintf('Loading %d/%d\n', imageI, numel(images));
    imageName = images(imageI).name;
    normalName = strrep(strrep(imageName, 'rgb_','nm_'),'.jpg','.mat');
    normalData = load([normalSource '/' normalName]);

    %set invalid normals to zero
    normalData.nx(~normalData.depthValid) = 0;
    normalData.ny(~normalData.depthValid) = 0;
    normalData.nz(~normalData.depthValid) = 0;

    %add to the sum and then the normalizer
    toAdd = cat(3,normalData.nx,normalData.ny,normalData.nz);
    resizedToAdd = max(min(imresize(toAdd,priorShape),1),-1);
    resizedValid = (imresize(normalData.depthValid, priorShape) == 1);
    resizedToAdd(~resizedValid) = 0;
     
    normalSum = normalSum + resizedToAdd;
    normalNormalizer = normalNormalizer + resizedValid;

end

normalPrior = normalSum ./ repmat((normalNormalizer + eps),[1,1,3]);
valid = normalNormalizer > (numel(images) / 2);

smoothSigma = 2;
for c=1:3
    prior = normalPrior(:,:,c);
    %set it to NaN, and catch all NaN values in the convolution
    prior(~valid) = NaN;
    normalPrior(:,:,c) = imfilter(prior,fspecial('gaussian',6*smoothSigma+1,smoothSigma));
end

valid = ~max(isnan(normalPrior),[],3);
%erode it a bit
valid = imerode(valid, ones(21,21));

fprintf('%d invalid entries\n',sum(~valid(:)));

%fill in the invalid parts of the image by extrapolation
[D,idx] = bwdist(valid);

%set the elements that aren't valid to the indices of the elements that 
%aren't valid
for c=1:3
    prior = normalPrior(:,:,c);
    prior(~valid) = prior(idx(~valid));
    normalPrior(:,:,c) = prior;
end

save([clusterSource  '/metadata/normalPrior.mat'], 'normalPrior')



