function xbeta_mat_to_txt(names, types, matdir)
% ----------------------
% Simple utility script to translate the ROI .mat files into
% .txt files for importing into Excel.


roifiles = spm_get('files', matdir, '*_params_xbeta.mat');

for i = 1:size(roifiles, 1)
    curr_roi = deblank(roifiles(i,:));
    load(curr_roi, '-mat');
    for j = 1:length(types)
        txtname = fullfile(matdir, [spm_str_manip(curr_roi, 'rtdu') '_' types{j} '.txt']);
        fid = fopen(txtname, 'w');
        fprintf(fid, 'Analysis: %s\n\n', types{j});
        fprintf(fid, 'Name\tMean\tVar\tN\tMin\tMax\t\n');
        curr_rname = strrep(spm_str_manip(curr_roi, 'rtdu'), '_params_xbeta', '');
        for k = 1:length(names)
            if ~isletter(names{k}(1))
                % we appended 'nonletter' to these variable names, so
                % look for that in variable names
                curr_var = eval(['nonletter' spm_str_manip(names{k}, 'u') '_' curr_rname '_' spm_str_manip(types{j}, 'u')]);
            else
                curr_var = eval([spm_str_manip(names{k}, 'u') '_' curr_rname '_' spm_str_manip(types{j}, 'u')]);
            end
            fprintf(fid, '%s\t%g\t%g\t%g\t%g\t%g\t\n', ...
                [names{k} '_' curr_rname], curr_var.mean, curr_var.var, ...
                curr_var.n, curr_var.min, curr_var.max);
        end
        fclose(fid);
    end
end
    
    