

function [outfiles, outpoints] = tal2mnigui(varargin)
% Converts coordinates to MNI brain best guess
% from Talairach coordinates
% FORMAT outfiles = tal2mnigui(varargin)
% where any argument will be considered as the
% infiles array (a matrix of strings (i.e., from spm_get)),
% or, if no argument is given, an array will be selected by the user.
% containing the filenames of .tal files to be converted.
% This wraps an interactive GUI shell around the Matthew Brett
% tal2mni script, allowing user selection of output dir.
% outfiles is the string matrix of output filenames;
% outpoints is the co-indexed cell array of output points for 
% each input file.
% Matthew Brett 2/2/01, Sue Whitfield  2001

if nargin == 0
    infiles = spm_get(Inf,'*.tal','Select TAL files');
else
    infiles = varargin{1};
end

outdir = spm_get(-1,'',...
			'Select directory to save output file(s).');
cdir = pwd;
cd(outdir);
k = size(infiles, 1);
        
for i=1:k
    name = deblank(infiles(i,:));
    inpoints = load(name);

%tal2mni code
dimdim = find(size(inpoints) == 3);
if isempty(dimdim)
  error('input must be a N by 3 or 3 by N matrix')
end
if dimdim == 2
  inpoints = inpoints';
end

% Transformation matrices, different zooms above/below AC
rotn = spm_matrix([0 0 0 0.05]);
upz = spm_matrix([0 0 0 0 0 0 0.99 0.97 0.92]);
downz = spm_matrix([0 0 0 0 0 0 0.99 0.97 0.84]);

inpoints = [inpoints; ones(1, size(inpoints, 2))];
% Apply inverse translation
inpoints = inv(rotn)*inpoints;

tmp = inpoints(3,:)<0;  % 1 if below AC
inpoints(:, tmp) = inv(downz) * inpoints(:, tmp);
inpoints(:, ~tmp) = inv(upz) * inpoints(:, ~tmp);
outpoints{i,1} = inpoints(1:3, :);
%end tal2mni code


outpoints{i,1} = round(outpoints{i,1});
[outpath, outname] = fileparts(infiles(i,:));

out{i,1} = fullfile(outdir, strcat(outname, '_mni.tal'));

     fid = fopen(deblank(out{i,1}),'w');
	     if fid == -1, error(['Unable to create new file - please check permissions', ...
								  ' in current directory.']); 
		  end
        
         fprintf(fid,'%d\t %d\t %d\n', outpoints{i,1});
        
  fclose(fid);
  
end
outfiles = char(out);
cd(cdir);