%takes the dumped clusters and makes and saves the median patches for transfer
globals;

dataTarget = CONFIG.processedSource;


clusterLocation = 'clusters/';
myRandomize;

splitClusterDirectory = [dataTarget '/' clusterLocation '/'];
clusters = dir([splitClusterDirectory '/c_*']);
clusterOrder = randperm(numel(clusters));
parfor cii=1:numel(clusters)
    ci = clusterOrder(cii);
    cname = clusters(ci).name;
    clusterDirectory = [splitClusterDirectory '/' cname];
    fprintf('Handling %s: ', cname);
    
    output = [clusterDirectory '/medianPatch.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);
    medianPatch = computePatchMedian(canonicalData);
    
    saveToMat(output, 'medianPatch', medianPatch);
    
    unlock([output '.lock']); 
end

splitClusterDirectory = [dataTarget '/' clusterLocation];
clusters = dir([splitClusterDirectory '/c_*']);
parfor ci=1:numel(clusters)
    cname = clusters(ci).name;
    fprintf('Handling %s\n', cname);
    computeScores([splitClusterDirectory '/' cname]);
end

