function writeOutClusters(patches, clusterAssignments, target)
    globals;
    normalDataSrc = CONFIG.normalSource;
    normalVisSrc = normalDataSrc;
    depthDataSrc = CONFIG.depthSource;
    if(~exist(target))
        mkdir(target);
    end
    numPatches = size(patches);
    numClusters = max(clusterAssignments);
    for ci=1:numClusters
        patchIndices = find(clusterAssignments==ci);
        if(numel(patchIndices) < 5)
            continue;
        end
        selectProb = numel(patchIndices) / 5;
        if rand(1) >= selectProb
            fprintf('Skipping due to randomization\n');
            continue;
        end 
        fprintf('Cluster %d: %d\n', ci, numel(patchIndices));
        clusterTarget = sprintf('%s/c_%d/',target,ci);
        if(~exist(clusterTarget))
            mkdir(clusterTarget);
        end

        for patchIndexI=1:5 
            patchIndex = patchIndices(patchIndexI); patch = patches(patchIndex);

            %dump rgb
            I = imread(patch.im(1:end));
            patchData = I(patch.y1:patch.y2,patch.x1:patch.x2,:);
            imwrite(patchData,sprintf('%s/patch_%d.jpg',clusterTarget,patchIndex)); 

            %dump normals

            %first, load the visualization
            [path,name,ext] = fileparts(patch.im(1:end));
            In = imread([normalVisSrc strrep(name,'rgb','nmvis') ext]);
            patchDataN = In(patch.y1:patch.y2,patch.x1:patch.x2,:);
            imwrite(patchDataN,sprintf('%s/normal_%d.jpg',clusterTarget,patchIndex)); 
            
            %next, load the actual data
            imageNormalData = load([normalDataSrc '/' strrep(name,'rgb','nm') '.mat']);
            patchNx = imageNormalData.nx(patch.y1:patch.y2,patch.x1:patch.x2); 
            patchNy = imageNormalData.ny(patch.y1:patch.y2,patch.x1:patch.x2); 
            patchNz = imageNormalData.nz(patch.y1:patch.y2,patch.x1:patch.x2); 
            patchValid = imageNormalData.depthValid(patch.y1:patch.y2,patch.x1:patch.x2); 


            %dump depth data 
            depthData = load([depthDataSrc '/' strrep(name, 'rgb','depth') '.mat']);
            patchDepth = depthData.depth(patch.y1:patch.y2,patch.x1:patch.x2);
    

            save(   sprintf('%s/patchdata_%d.mat',clusterTarget,patchIndex), ...
                    'patchNx','patchNy','patchNz','patchDepth','patchValid');

            

            bbox = [patch.x1, patch.y1, patch.x2, patch.y2];
            fh = fopen(sprintf('%s/filename_%d.txt',clusterTarget, patchIndex),'w');
            fprintf(fh, [name '\n']);
            fclose(fh);
            dlmwrite(sprintf('%s/bbox_%d.txt',clusterTarget, patchIndex), bbox);
            
            Ih = size(In,1);
            Iw = size(In,2);
            dlmwrite(sprintf('%s/imagedim_%d.txt',clusterTarget, patchIndex), [Ih, Iw]);
        end
    end
end
