globals;
%the target and the base name. Chunk folders will be of the form %s/%s_%d
targetBase = CONFIG.processingDir;
targetName = CONFIG.processingName;
joinedName = sprintf('%s_%d',CONFIG.processingName,1);
commonSource = [targetBase '/' joinedName '/div2/train/0/'];

%figure out how many chunks to look for
chunkData = load([commonSource '/FIG_PATCH_CLUSTERS_REF.mat']);
numClusters = size(chunkData.centers,1);
numChunks = ceil(numClusters / perChunk);


subfolder = {'/div2/','/div2/train/'};
batchSource = subfolder{end};
%Grab the last iteration's clusters and detectors
iterFolders = {'4/','5/'};
filens = {'detectors_MINED.mat','FIG_PATCH_CLUSTERS_REF.mat'};

joinedTarget = [targetBase '/' joinedName];

if ~exist(joinedTarget)
    mkdir(joinedTarget);
end

for subI=1:numel(subfolder)
    mkdir([joinedTarget '/' subfolder{subI}]);
end

for chunkI=1:numChunks
    chunkSrc = sprintf('%s/%s%d/%s/batch-%d',targetBase,targetName,chunkI,batchSource,chunkI);
    chunkTarget = sprintf('%s/%s/%s/batch-%d',targetBase,joinedName,batchSource,chunkI);

    if ~exist(chunkTarget)
        mkdir(chunkTarget);
    end

    %for every iter folder
    for iterFolderI=1:numel(iterFolders)
        iterFolder = iterFolders{iterFolderI};
        if ~exist([chunkTarget '/' iterFolder])
            mkdir([chunkTarget '/' iterFolder]);
        end
        
        for filenI=1:numel(filens)
            filen = filens{filenI};
            fprintf('Copying %s/%s\n',iterFolder,filen);
            fileSrc = [chunkSrc '/' iterFolder '/' filen];
            fileTarget = [chunkTarget '/' iterFolder '/' filen];
            if exist(fileSrc)
                copyfile(fileSrc,fileTarget);
            end
        end 
    end

end 

