#
#--> xdvi(a);
#
# NOTE: this function is a Unix only command for systems that have
# support latex and xdvi.  The intention is to be able to quickly view
# an expression in a pretty printed form.
#
# 1: Create a LaTeX document (style article) (default: 10pt)
#    in the file (default `temp.tex`) which contains the latex output
#    for the expression a enclosed in \[ \] brackets.
# 2: Run `latex' on this file and then run xdvi on the output
#
#--> xdvi([a1,a2,...,an]);
#
# Creates LaTeX output for the expressions a1, a2, ..., an on separate
# lines, i.e. each expression is enclosed in \[ \] brackets
#
#--> xdvi(...,filename=f,pointsize=n,size=s);
#
# Optional arguments are
#
# filename = f: where f is of type string -- default: temp
# pointsize = n: where n is one of 10, 11, 12 -- default: 10
# size = s: where s is one of {small,large,Large,LARGE,Huge}
#
# This routine uses the Maple library routine latex to convert a Maple
# expression into latex -- hence no linebreaking at this time.
#
# Users are free to modify this code, for example to work with plain TeX.
#
# Author: MBM Jan/92
#

macro( SIZES = {small,large,Large,LARGE,Huge} );

xdvi := proc(x) local s,e,f,n,p,texfile,xdvifile;

if not type(x,list) then RETURN( xdvi([x],args[2..nargs]) ) fi;

p := 10; # default point size
f := temp; # default file
s := NULL; # default size

for e in [args[2..nargs]] do
    if not type(e,string=anything) then ERROR(`invalid option`,e) fi;
    n := op(1,e);
    if n = 'filename' then
	f := op(2,e); 
	if not type(f,string) then
	    ERROR(`filename must be a string`,e)
	fi;
	next
    fi;
    if n = 'pointsize' then
	p := op(2,e);
	if not member(p,{10,11,12}) then 
	    ERROR(`point size must be 10, 11, or 12: got`,p)
	fi;
	next
    fi;
    if n = 'size' then
	s := op(2,e);
	if not member(s,SIZES) then
	    ERROR(`size must be one of`,SIZES);
	fi;
	next
    fi;

    ERROR(`unknown option`,n)
od;
	
n := length(f);
if substring(f,n-3..n) = '`.tex`' then f := substring(f,1..n-4) fi;

texfile := cat(f,`.tex`);
lprint(`generating latex output ...`);

interface(quiet=true);
writeto(texfile);
`xdvi/print_header`(p,s);
for e in x do
    lprint(`\\[`);
    latex(eval(e,1));
    lprint(`\\]`);
od;
`xdvi/print_trailer`();

writeto(terminal);
interface(quiet=false);

lprint(`running latex ...`);
system(cat(`latex `,texfile));

lprint(`running xdvi ...`);
xdvifile := cat(f,`.dvi`);
system(cat(`xdvi `,xdvifile,` &`));
	
lprint(`exiting tex2xdvi`);

end:

`xdvi/print_header` := proc(p,s)
lprint(`% LaTeX output from Maple: M.B. Monagan`);
if p = 10 then lprint(`\\documentstyle{article}`) fi;
if p > 10 then lprint(`\\documentstyle[`.p.`pt]{article}`) fi;
lprint(`\\begin{document}`);
lprint(`{`);
if nargs > 1 then lprint(`\\`.s) fi;
end:

`xdvi/print_trailer` := proc()
lprint(`}`);
lprint(`\\end{document}`);
end:

# save `xdvi.m`;
# quit
