function artdetect_repair
% FORMAT artdetect_repair 
% ----------------------------------

% Helper function for artdetect4.m.  We offer three choices for
% outlier elimination: mean insertion, interpolation, and simple
% removal.  Mean insertion replaces each outlier scan with a 
% mean image constructed from all scans in the session.  Interpolation
% replaces each outlier scan with an average of the scans before 
% and after the outlier (or the two scans after if the outlier is the
% first scan, or the two scans before, if the outlier is the last scan).
% Removal is just what it sounds like - the offending scan is simply
% deleted from the timecourse.  Every outlier scan is safely saved, 
% though, with 'outlier_' appended to its filename.
% ---------------------------------
% Jeff Cooper, November 2002

% ----------------------
% Interrogate GUI
% ----------------------

%keyboard;
handles = guihandles;
rng = str2num(get(handles.rangenum, 'String'));
out_idx = round(str2num(get(handles.indexedit, 'String')));
P = getappdata(gcbo, 'data');


% ----------------------
% Data editing
% ----------------------
%keyboard;
cdir = pwd;
cd(fileparts(P(1,:)));

intfig = spm('CreateIntWin', 'on');
inter_method = spm_input_ui('Which repair method?', 1, 'b', 'Mean|Interp|Remove', [1;2;3], 2);

meth_string = '';
if inter_method == 1
    meth_string = 'mean insertion';
    % remove outliers in question from mean calculation
    meanP = P;
    meanP(out_idx,:) = [];
    %for i = 1:length(out_idx)
    %    meanP(out_idx(i),:) = [];
    %end
    spm_mean_ui(meanP);
    % Don't forget that this "mean" image is created with spm_add and 
    % scalefactors in the image headers.  Which means we need to copy
    % the header later on to make sure spm_global is using proper
    % scalefactors to read the data.
    mean_img = fullfile(pwd, 'mean.img');
    mean_hdr = fullfile(pwd, 'mean.hdr');
    
end
if inter_method == 2
    meth_string = 'interpolation';
end
if inter_method == 3
    meth_string = 'removal';
end

fprintf('\n The scans with indices %s are being repaired by %s.\n', num2str(out_idx), meth_string);
fprintf('\n These outlier scans will be saved in the same directory');
fprintf('\n with ''outlier_'' appended to their filename.\n');

for i = 1:length(out_idx)
    fprintf('\nRepairing scan %g...\n', out_idx(i));
    curr = P(out_idx(i),:);
    [currpath, currname, currext] = fileparts(curr);
    curr_hdr = fullfile(currpath, [currname '.hdr']);
    copyname = ['outlier_' currname currext];
    copyname_hdr = ['outlier_' currname '.hdr'];
    copy = fullfile(currpath, copyname);
    copy_hdr = fullfile(currpath, copyname_hdr);
    system(['cp ' curr ' ' copy]);
    system(['cp ' curr_hdr ' ' copy_hdr]);
    %copyfile(curr, copy); % now we have a clean copy of this file preserved.
    %copyfile(curr_hdr, copy_hdr); % ditto the header

    if inter_method == 1;
        delete(curr);
        delete(curr_hdr);
        system(['cp ' mean_img ' ' curr]);
        system(['cp ' mean_hdr ' ' curr_hdr]);
        %copyfile(mean_img, curr);
        %copyfile(mean_hdr, curr_hdr);
        continue;
    end

    if inter_method == 2;
        if out_idx(i) == 1 % i.e., this is the first scan
            if (size(P,1) < 3)
                error('Cannot interpolate first image: less than three scans.');
            end
            im_in = spm_vol([P(2,:);P(3,:)]);
            im_map = spm_vol(curr);
            spm_imcalc(im_in,im_map,'(i1+i2)/2');
            continue;
        else 
            if out_idx(i) == size(P,1) %i.e., this is the last scan
                im_in = spm_vol([P(out_idx(i)-2,:);P(out_idx(i)-1,:)]);
                im_map = spm_vol(curr);
                spm_imcalc(im_in,im_map,'(i1+i2)/2');
                continue;
            end
            im_in = spm_vol([P(out_idx(i)-1,:);P(out_idx(i)+1,:)]);
            im_map = spm_vol(curr);
            spm_imcalc(im_in, im_map, '(i1+i2)/2');
            continue;
        end
    end

    if inter_method == 3;
        delete(curr);
        delete(curr_hdr);
        continue;
    end

end
fprintf('\nDone!\n');
close(intfig);


cd(cdir);


