if (~exist('aggexp')),
	% define the experiments
	several_experiments;
	% compute/plot all the stats
	aggexp = aggregate(experiment);
end

% dump the results as TeX code
[fid,msg] = fopen('tables/exp-results.tex','w');
if (fid<=0),
	error(msg);
end

for i=1:length(aggexp),
	exp = aggexp(i);
	fns = fieldnames(exp.summary);
	for j=1:length(fns),
		fn = char(fns(j));
		package = getfield(exp.summary,fn);
		value = package.value;
		units = package.units;
		fprintf(fid, '\\newcommand{\\%sB}{%s~%s}\n', ...
			collapse(fn), imprecision(value.b,2), units.b);
		fprintf(fid, '\\newcommand{\\%sM}{%s~%s}\n', ...
			collapse(fn), imprecision(value.m,2), units.m);
		fprintf(fid, '\\newcommand{\\%sBTbl}{%s}\n', ...
			collapse(fn), imprecision(value.b,2));
		fprintf(fid, '\\newcommand{\\%sMTbl}{%s}\n', ...
			collapse(fn), imprecision(value.m,2));

		sigma_val = imprecision(value.sgm,2);
		rr_val = imprecision(value.rr,2);

		% report on any stats not really amazing
		statEx = '';
		% I'm generally going to report sigma and R^2, so they don't
		% go in the Exceptions column.
		if (log10(value.mci/value.m) > -3),
			statEx = strcat(statEx, sprintf(', $%s%s$~%s', 'b_1 \pm', ...
				imprecision(value.mci,2), units.mci));
		end
		if (log10(value.bci/value.b) > -3),
			statEx = strcat(statEx, sprintf(', $%s%s$~%s', 'b_0 \pm', ...
				imprecision(value.bci,2), units.bci));
		end
		if (log10(value.sgm/value.b) > -3),
%			statEx = strcat(statEx, sprintf(', $%s%s$~%s', '\sigma = ', ...
%				imprecision(value.sgm,2), units.sgm));
		else
			sigma_val = '';
		end
		if (value.rr<0.985),
%			statEx = strcat(statEx, sprintf(', $%s%s$', 'R^2 = ', ...
%				imprecision(value.rr,2)));
		else
			rr_val = '';
		end
		if (length(statEx)>1),
			statEx = statEx(2:end);	% crop the comma
		end
		fprintf(fid, '\\newcommand{\\%sEx}{%s}\n', ...
			collapse(fn), statEx);

		fprintf(fid, '\\newcommand{\\%sRr}{%s}\n', collapse(fn), rr_val);
		fprintf(fid, '\\newcommand{\\%sSgm}{%s}\n', collapse(fn), sigma_val);

%		if (fn(end-1)=='c' & fn(end)=='i'),
%			base = fn(1:end-2);
%			pbase = getfield(exp.summary, base);
%			pci = getfield(exp.summary, fn);
%			fprintf(fid, '\\newcommand{\\%s}{%s & %s %s}\n', ...
%				collapse([base,'_tbl']), imprecision(pbase.value,2), ...
%				'$\pm$', imprecision(pci.value,2));
%		end
	end
end

table = defTables;

for i=1:length(table),
	if (length(table(i).tablename)>0),
		% ignore undefined tables
		gentable(aggexp, table(i));
	end
end

% other funny values
s1 = extractRows(aggexp, {'sfbw_sh_loc_macs'});
s2 = extractRows(aggexp, {'sfbw_sh_loc_ident'});
fprintf(fid, '\\newcommand{\\%s}{%s %s}\n', ...
	'sfbwMacsMinusIdent', imprecision(s1.b_value-s2.b_value,2), s1.b_units);
fclose(fid);
