%This program extracts the mean values from the selected data files for the specified ROI.
%last modified, 2/7/02 Sue Whitfield


function varargout=roi_extract(ImgF, roi_path_array, OutTxt);


if nargin==0
  ImgF=spm_get(Inf,'*.img','Select files to extract from');
end

if nargin<2
  roi_path_array=spm_get(Inf,'*.tal','Select .tal files defining ROIs');
end

if nargin<3, 
  tmp = input('\nWould you like to write text files? [y|n] : ','s');
  if strcmpi(tmp,'y'), OutTxt='text'; else OutTxt=''; end
end


for r = 1:size(roi_path_array, 1)
roi_path = deblank(roi_path_array(r,:));

% Read in coordinates into ROImm
% -------------------
XYZmm = spm_load(roi_path)';
if size(XYZmm,1)~=3,error('The .tal should have 3 columns.'),end

VF = spm_vol(ImgF);

for i = 1:length(VF)

    
    % Convert to XYZmm to pixel coordinates in XYZ
   iM=inv(VF(i).mat);
   XYZ = iM(1:3,:)*[XYZmm; ones(1,size(XYZmm,2))];
   
     % resample data at voxel centres of ROI

  d    = spm_sample_vol(VF(i),...
			XYZ(1,:),XYZ(2,:),XYZ(3,:),1);
  
  % mask with NaNrep
  NaNrep = spm_type(VF(i).dim(4),'nanrep');
  data = d(d~=NaNrep);
  d = data;  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  d = d(find(~isnan(d)));
 %%%%%%%% 
 
 ROIdat(i,1) = mean(d);
      
end



% work out output arguments
% -------------------------
if ~strcmpi(OutTxt,'text'), varargout{r}=ROIdat; end



% write a text files if requested
% --------------------------------
if strcmpi(OutTxt,'text')
   
   [foo name_roi]  =fileparts(roi_path);
   name_dat=[name_roi,'.txt'];
	
     fid = fopen(name_dat,'w');
	     if fid == -1, error(['Unable to create new file - please check permissions', ...
								  ' in current directory.']); 
		  end
   
     fprintf(fid,'%4.4f\n', ROIdat);
     fclose(fid);

     fprintf('\n\n------------------------------------------------------------');
     fprintf('\nA new file ''%s'' was created in',char(name_dat));
     fprintf('\n%s\n',pwd);
     fprintf('\nIt contans the average ROI value for each selected .img file.');
     fprintf('\n------------------------------------------------------------\n\n');
	  
end

end

