%David Fouhey
%Demo surface normal evaluation code

%E1 contains the errors on raw depth mask valid pixels
%E2 contains the ones on the projection mask
E1 = {}; E2 = {};
parfor i=1:1449
    fprintf('%d/%d\n',i,1449);
    predFile = sprintf('pathToPredictions/predictionPaper/rgb_%06d.jpg.nmap.mat',i);

    if ~exist(predFile) 
        continue; 
    end

    normalLocation = 'luborNormals/normals/';
    maskData = load(sprintf('pathtoNYU/rawD/depth_%06d.mat',i));
    gtData = load(sprintf('%s/%06d.mat',normalLocation,i)); 

    N = gtData.N;
    N = bsxfun(@rdivide,N,sum(N.^2,3).^0.5+eps);

    pdata = load(predFile);
    P = pdata.nd.denseMaps{end}; 
    P = bsxfun(@rdivide,P,sum(P.^2,3).^0.5+eps);

    %assume invalid
    depthValid = zeros([size(N,1),size(N,2)]);
    %projection mask
    depthValid(45:471,41:601) = 1;
    depthValidWOMask = depthValid;
    %mask out ones where kinect gives no data
    depthValid = depthValid .* (maskData.depth~=0);
   
    %error map
    theta = acosd(min(1,max(-1,sum(N.*P,3))));

    E1{i} = theta(find(depthValid));    
    E2{i} = theta(find(depthValidWOMask));
end

%accumulate them
A1 = cat(1,E1{:});
A2 = cat(1,E2{:});

fprintf('With Mask:           %f %f %f %f %f %f\n', [mean(A1(:)),median(A1(:)),mean(A1.^2).^0.5,mean(A1<11.25),mean(A1<22.5),mean(A1<30)]);
fprintf('Without Mask:        %f %f %f %f %f %f\n', [mean(A2(:)),median(A2(:)),mean(A2.^2).^0.5,mean(A2<11.25),mean(A2<22.5),mean(A2<30)]);

