function xbeta_mat_to_txt_session(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});
        curr_rname = strrep(spm_str_manip(curr_roi, 'rtdu'), '_params_xbeta', '');
        sample_var = eval([spm_str_manip(names{1}, 'u') '_' curr_rname '_' spm_str_manip(types{j}, 'u')]);
        fprintf(fid, 'Name\t');
        for s = 1:length(sample_var.mean)
            fprintf(fid, 'Mean (sess %s)\t', int2str(s));
            fprintf(fid, 'Var (sess %s)\t', int2str(s));
            fprintf(fid, 'N (sess %s)\t', int2str(s));
            fprintf(fid, 'Min (sess %s)\t', int2str(s));
            fprintf(fid, 'Max (sess %s)\t', int2str(s));
        end
        fprintf(fid, '\n');
        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', [names{k} '_' curr_rname]);
            for s = 1:length(sample_var.mean)
                fprintf(fid, '%g\t%g\t%g\t%g\t%g\t', ...
                    curr_var.mean(s), curr_var.var(s), ...
                    curr_var.n(s), curr_var.min(s), curr_var.max(s));
            end
            fprintf(fid, '\n');
        end
        fclose(fid);
    end
end
    
    