function slComplete(searchlight, removeFiles)
% slComplete(searchlight, removeFiles)
% SEARCHLIGHT - COMPLETE
% ---------------------------------------------------------
% Verifies presence of all necessary portions of searchlight, finishing by
% inserting all of them into a parameter map for loading into mrVista.
%
% INPUTS
%   searchlight - Structure generated by slInit.
%   removeFiles - Off by default, when set to true it will clean up files
%       as it reads them in.
%
% OUTPUTS
%   N/A
%
% USAGE
%   After running a searchlight, passing it to slComplete to construct a
%   parameter map.  In this case, we choose to remove the files.
%       searchlight = slInit(...);
%       slRun(searchlight, ...);
%       slComplete(searchlight, true);
%
% See also SLINIT, SLRUN, SLSPAWN, SVMINIT.
%
% renobowen@gmail.com [2010]
%

if notDefined('removeFiles'), removeFiles = false; end

totalProcesses = searchlight.processes * searchlight.partitions;
if (isSearchlightComplete(searchlight, totalProcesses))
    processSearchlight(searchlight, totalProcesses, removeFiles);
end

end

function bool = isSearchlightComplete(searchlight, totalProcesses)
for i = 1:totalProcesses
    if (~exist(sprintf('%s/%s/searchlight%04d.mat', searchlight.path, searchlight.tmpDir, i), 'file'))
        bool = false;
        return;
    end
end
bool = true;
end

function processSearchlight(searchlight, processes, removeFiles)
svm = searchlight.svm;
svm = rmfield(svm, 'data'); % this is to save space

for i = 1:processes
    filename = sprintf('%s/%s/searchlight%04d.mat', searchlight.path, searchlight.tmpDir, i);
    tmp = load(filename);
    nCenters = size(tmp.centers, 2);
    for j = 1:nCenters
        if (~isempty(tmp.meanAccs(j)))
            if (strcmpi(searchlight.searchView, 'gray'))
                map{1}(tmp.centers(1, j)) = tmp.meanAccs(j);
            else
                map{1}(tmp.centers(1, j), tmp.centers(2, j), tmp.centers(3, j)) = tmp.meanAccs(j);
            end
        end
    end
    if (removeFiles), delete(filename); end
end
growBy = tmp.growBy;
fprintf('done.\n');

if (removeFiles), rmdir(sprintf('%s/%s', searchlight.path, searchlight.tmpDir)); end

filename = sprintf('%s/%s.mat', searchlight.path, searchlight.tmpDir);
mapName = 'searchlight';
if exist('mapBootstrap','var')
    save(filename, 'map', 'mapName', 'growBy', 'svm', 'mapBootstrap', '-v7.3');
else
    save(filename, 'map', 'mapName', 'growBy', 'svm', '-v7.3');
end
fprintf('Saved to: %s\n', filename);

end
