 function hwprint(mfile, psfile)
%function hwprint(mfile, ps_or_pdf_file)
% This Matlab m-file creates and executes a very short LaTeX file
% to create a short document that consists of the current figure(s)
% combined with a printout of the user-supplied mfile.
% The final output is stored in "psfile" (or hprint.ps by default),
% which can be previewed with "ghostview" or printed with "lpr".
% This should work on unix machines (including Mac OS X) and CAEN pc's.
% Use "ghostview file.ps" in unix to preview the output before printing.
%
% Jeff Fessler 1/5/00
%
% Modified by Eran Bashan on 2005-1-12 for multiple figures.
% Modified by Chuck Divin on 2005-1-15 for CAEN Windows printing.
% Modified by Gyemin Lee on 2005-1-24 for pdf.

if nargin == 1 && isequal(mfile, 'test'), hwprint_test, return, end % self test

fn = 'hprint';		% file name prefix for all temporary files
tmp.tex = [fn '.tex'];	% temporary .tex file
tmp.dvi = [fn '.dvi'];
tmp.log = [fn '.log'];
tmp.aux = [fn '.aux'];

if nargin < 2, psfile = [fn '.ps']; end
if nargin < 1, help(mfilename), error 'supply mfile name', end
if exist(mfile) ~= 2
	if exist([mfile '.m'])==2, mfile = [mfile '.m'];
	else, error(['cannot find file ' mfile]); end
end
if exist(tmp.tex, 'file'), error([tmp.tex ' already exists']), end

% Identify the figures and create temporary EPS file names
h = findobj(get(0,'children'), 'flat', 'type', 'figure');
if isempty(h), error('No figure to print.  Run your mfile first!'); end
nFigure = length(h);
for ii = 1:nFigure
	epsName{ii} = sprintf([fn '%d.eps'], ii);
end

% Determine system dependent variables and commands
if ispc
	try
		[status, user] = system('echo %USERNAME%');
	catch
		status = 0;
		user = 'unknown';
	end
	latexPath = 'S:\CAEN\MikTex 2.3\miktex\bin\';
	latex = ['"' latexPath 'latex.exe"'];
	dvips = ['"' latexPath 'dvips.exe"'];
	dvipdfm = ['"' latexPath 'dvipdfm.exe"'];
	if exist(latex(2:end-1))~=2, % exist command doesn't like the quotes
		error(['Cannot find latex.exe, please update "latexPath" variable in "' mfilename '".']);
	end
else
	try
		[status, user] = system('whoami');
	catch
		status = 0;
		user = 'unknown';
	end
	latex = 'latex';
	dvips = 'dvips';
	dvipdfm = 'dvipdfm';
end

% Create LaTeX file contents
head = {...
	'\documentclass{article}';
	'\usepackage{times}'
	'\usepackage{moreverb}';
	'\usepackage[dvips]{graphicx}';
	'\setlength{\textwidth}{7in}';
	'\setlength{\textheight}{9.5in}';
	'\setlength{\oddsidemargin}{-0.25in}';
	'\setlength{\evensidemargin}{\oddsidemargin}';
	'\setlength{\topmargin}{-0.25in}';
	'\setlength{\headsep}{0pt}';
	'\setlength{\headheight}{0pt}';
	'\begin{document}';
	};
for ii = 1:nFigure
	middle{ii} = ['\includegraphics[width=\textwidth]{' epsName{ii} '}'];
end
tail = { ...
	['\verbatimtabinput{' mfile '}'];
	['Created \today\ for ' user];
	'\end{document}';
	};
body = {head{:}, middle{:}, tail{:}};

% Write LaTeX file
fid = fopen(tmp.tex, 'w');
for ii = 1:length(body)
	fprintf(fid, '%s\n', body{ii});
end
if fclose(fid), error fclose, end
if ~exist(tmp.tex, 'file'), error fileproblem, end

% save current figure(s)
for ii = 1:nFigure
	print(h(ii), epsName{ii}, '-depsc');
end

% latex the file and convert the dvi file to postscript or pdf

% replace ' ' with ' --quiet ' to turn off LaTeX screen output
if system([latex ' ' tmp.tex])
	warning 'texproblem'
end

if ~isempty(strfind(lower(psfile), '.pdf')) % not working on my mac
	% replace .... " -q " to .....
	com = [dvipdfm ' -o ' psfile ' ' tmp.dvi];
	if system(com)
		warning dviproblem
	end
else
	% replace .... " -q " to .....
	com = [dvips ' ' tmp.dvi ' -o ' psfile];
	if system(com)
		warning dviproblem
	end
end

% clean up.  Default to yes
if ~strcmp(input('clean up temporary files? [y|n] ', 's'), 'n')
	delete([fn '*.eps']);
	delete(tmp.tex)
	delete(tmp.dvi)
	delete(tmp.log)
	delete(tmp.aux)
end


function hwprint_test % basic test of hwprint.m
t = linspace(0,4,101);
figure(1)
subplot(211), plot(t, cos(t))
subplot(212), plot(t, cos(t))
figure(2)
imagesc(rand(10,10))
hwprint('hwprint.m', 'tmp.ps')
