function img_truncate(varargin); 
% VOL_TRUNCATE Truncate an SPM format volume with a specified cut_off.
%
% FORMAT = vol_truncate;
% will ask for a cut_off to truncate at
%
% FORMAT = vol_truncate(cut_off);
% truncate at the specified cut_off
% --------------------------------------------------------------

if nargin == 0, cut_off=input('Please enter cut-off to truncate at : ');
   elseif nargin == 1, cut_off = varargin{1};
   elseif nargin >1, error('Too many input arguments.');
end

% get the volume to work on and load the intensities in Y
% --------------------
vol_path = spm_get(1,'*.img','Please select image to truncate.');

% load the volume
% ---------------
if ischar(vol_path)
  vol = spm_vol(vol_path);
end


%-Read in image data
%-----------------------------------------------------------------------
Y = spm_read_vols(vol,0);

% initialize the corrected output volume Yc
Ytr=zeros(vol.dim(1:3));

fprintf('\nPlease wait - computing ...  \n\n');

% begin looping through planes
% ----------------------------
for p = 1:vol.dim(3);

	img   = spm_slice_vol(vol,spm_matrix([0 0 p]),vol.dim(1:2),1);
        
        img_tr = img;
        img_tr(find(img>cut_off))=cut_off;

	Ytr(:,:,p) = img_tr;

        clear img img_tr;

% end looping through planes
% ---------------------------
end

% write corrected image (trunc.img)
% ==================================

tmp = max([findstr('/',vol_path),findstr('\',vol_path)]);

Ytr_vol = vol;
Ytr_vol.fname = [vol_path(1:tmp),'t',vol_path(tmp+1:end)];
Ytr_vol.descrip=['truncated at Y = ', sprintf('%d',cut_off)];

spm_write_vol(Ytr_vol,Ytr);

    fprintf('\n\nThe new image %s was saved in\n',Ytr_vol.fname(tmp+1:end));
    fprintf('%s',Ytr_vol.fname(1:tmp));















