function outfiles = mm2img(varargin)
%Given a list of .tal files - or, if no argument is given, the user 
% selects a list - mm2img creates an ROI in analyze format.
%sue, last updated 2/28/02
%updated by jeff 9/23/02

if nargin < 2
    ROI = spm_get(1,'.img',...
         ['select template image for ROI(s)'] ); 
 else
     ROI = varargin{2};
 end
     
v = spm_vol(ROI)
[Y,XYZ] = spm_read_vols(v);


if nargin==0
    %------------------------------------- 
    %  Load desired ROI file
    %-------------------------------------
    %fprintf('Please, select desired ROI file(s). \n'); 
    fprintf('Please, select desired TAL file(s). \n'); 

    roi_fulloc= spm_get(inf, '.tal', 'Select  roi_name.tal  file(s).')
    fprintf('Done.\n\n\n');
else
    roi_fulloc = varargin{1};
end
%---------------------------------------------------
% Select output filename
if nargin < 3
    outdir = spm_get(-1,'',...
			'Select directory to save output .img file(s).');
else 
    outdir = varargin{3};
end

%------------------------------------------
%  Load ROI files and directory
%------------------------------------------  %'/'  ->  '\'
for i=1:size(roi_fulloc,1)

    [ROI_path_take{i},ROI_name_take{i}] = fileparts(roi_fulloc(i,:));
   
    %--- get the path to and the name of this roi ---
   %ROI_path_take{i} = roi_fulloc(i,...
   %       (1:max(find(roi_fulloc(i,:)=='/')) )...
				%  );   


   %ROI_name_take{i}= roi_fulloc(i,...
    %  (...
   %     (max(find(roi_fulloc(i,:)=='/'))+1)...
   %     :...
   %     (max(find(roi_fulloc(i,:)=='.'))-1)...
   %    )...
                                  %);
    %--- load mm coordinates data for this roi ---
   ROI_tal_take{i}= load(fullfile(ROI_path_take{i}, [ROI_name_take{i} '.tal'])); 
   
    dimdim = find(size(ROI_tal_take{i}) == 3);
    if isempty(dimdim)
        error('input must be a N by 3 or 3 by N matrix')
    end
    if dimdim == 1
        ROI_tal_take{i} = ROI_tal_take{i}';
    end

end 


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   
                        
 vinv = inv(v.mat); %matrix converting mm->voxels
 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:size(ROI_tal_take,2)
    ROI_tal = ROI_tal_take{i};
    
    Y_roital = zeros(size(Y)); 

%roitaltotvox = [];

for j = 1:size(ROI_tal,1)
   
   ROI_talx = round((vinv*([ROI_tal(j,:) 1]'))');
    %if (~(isempty(find(ROI_talx > 109))))
    %    keyboard;
    %end

   
   Y_roital(ROI_talx(1),ROI_talx(2),ROI_talx(3)) = 1;
      %roitaltotvox = [roitaltotvox; ROI_talx];
end

%v.fname = 'unnorm_nBA4';
%v.fname = ROI_tal;
out{i} = fullfile(outdir, [ROI_name_take{i} '.img']);
v.fname = out{i};

%keyboard;
spm_write_vol(v,Y_roital)
end

outfiles = char(out);