% get all files in the working directory
% find the DCM*.mat in it
% and let SPM estimate the not-estimated DCM*.mat files
%
% 2012-08-21 Ingo Keck (ingokeck@ingokeck.de)
files = dir;
% now iterate over all files
for n=1:size(dir,1)
    % ignore '.' and '..' and directories
    %if ~strcmp(files(n).name,'.') && ~strcmp(files(n).name,'..')
    if files(n).isdir == false && length(files(n).name) > 7
        % select DCM*.mat files
        if strcmpi(files(n).name(end-3:end),'.mat') && strcmpi(files(n).name(1:3),'DCM')
            [dcmpath,dcmfile,dcmext] = fileparts(files(n).name);           
            % look for a file lock
            if ~exist(fullfile(dcmpath,[dcmfile '_lock']),'dir')
                % load DCM*.mat
                DCM = load(files(n).name);
                % check if the DCM has not been estiomated
                if isfield(DCM,'DCM')
                    if ~isfield(DCM.DCM,'Pp')
                        clear DCM
                        mkdir(fullfile(dcmpath,[dcmfile '_lock']))
                        try
                            DCM = spm_dcm_estimate(files(n).name);
                            %save(files(n).name,'DCM')
                        catch ME
                            % do not stop for errors but give feedback
                            fprintf('error in %s:\n',files(n).name)
                            disp(ME)
                        end
                        rmdir(fullfile(dcmpath,[dcmfile '_lock']))
                    end
                end
            end
        end
    end
end