dataTarget = CONFIG.processedSource;
clusterLocation = 'clusters/';

myRandomize;

splitClusterDirectory = [dataTarget '/' clusterLocation '/'];
clusters = dir([splitClusterDirectory '/c_*']);
clusterOrder = randperm(numel(clusters));

for cii=1:numel(clusters)
    ci = clusterOrder(cii);
    cname = clusters(ci).name;
    clusterDirectory = [splitClusterDirectory '/' cname];
    fprintf('Handling %s: ', cname);
    
    output = [clusterDirectory '/patchStats.mat'];

    if exist(output) || isLocked([output '.lock']);
        fprintf('skipping\n');
        continue;
    end
    
    fprintf('computing\n');
    patches = {};
    patchData = dir([clusterDirectory '/patchdata*.mat']);

    for pi=1:numel(patchData)
        patches{pi} = load([clusterDirectory '/' patchData(pi).name]); 
    end

    canonicalData = canonicalizePatchData(patches);
    
    medianPatchData = load([clusterDirectory '/medianPatch.mat']);
    medianPatch = medianPatchData.medianPatch;

    thetaMap = zeros(size(canonicalData.patchNx));
    %get the normalized surface normals for the median patch
    mnx = medianPatch.patchNx; mny = medianPatch.patchNy; mnz = medianPatch.patchNz;
    mpNorm = (mnx.^2 + mny.^2 + mnz.^2).^0.5;
    mnx = mnx ./ (mpNorm+eps); mny = mny ./ (mpNorm+eps); mnz = mnz ./ (mpNorm+eps);

    for pi=1:numel(patchData)
        %get normalized surface normals
        nx = canonicalData.patchNx(:,:,pi); ny = canonicalData.patchNy(:,:,pi); nz = canonicalData.patchNz(:,:,pi);
        patchNorm = (nx.^2 + ny.^2 + nz.^2).^0.5;
        nx = nx ./ (patchNorm+eps); ny = ny ./ (patchNorm+eps); nz = nz ./ (patchNorm + eps);

        dp = min(max(-1,nx.*mnx + ny.*mny + nz.*mnz),1.0); 
        thetaMap(:,:,pi) = acos(dp);
    end

    patchStats.thetaMax = nanmax(thetaMap,[],3);
    patchStats.thetaMean = nanmean(thetaMap,3);

    %compute unbiased std; specifying which is required when 
    %specifying a dimension
    patchStats.stdNx = nanstd(canonicalData.patchNx,0,3);
    patchStats.stdNy = nanstd(canonicalData.patchNy,0,3);
    patchStats.stdNz = nanstd(canonicalData.patchNz,0,3);
    
    save(output, 'patchStats');
    
    unlock([output '.lock']); 
end


