#!/usr/bin/perl -w
use strict;
use FindBin;
use lib "$FindBin::RealBin/../lib";
use Getopt::Long qw(:config no_ignore_case);
use Pod::Usage;
use LaTeXML;
use LaTeXML::Util::Pathname;

# latexmlpost

use File::Spec;
use LaTeXML::Post;
#use LaTeXML::Post::Writer;
use LaTeXML::Util::ObjectDB;

#**********************************************************************
# Parse command line

my $identity = "latexmlmath (LaTeXML version $LaTeXML::VERSION)";
my($verbosity,$strict,$noparse,$includestyles)=(-1,0,0,0);
my ($destination,$help,$showversion)=('','');
my ($documentid);
my($mathimage,$mag)=(undef,1.75);
my($pmml,$linelength)=(undef,undef);
my $xmath=undef;
my $cmml=undef;
my $om=undef;

my @paths = ('.');
my (@preload,@debugs);
GetOptions(
	   # No provision for parallel output (yet)
	   "mathimage=s"               => \$mathimage,
	   "magnification=f"           => \$mag,
	   "presentationmathml|pmml=s" => \$pmml,
	   "linelength=i"              => \$linelength,
	   "contentmathml|cmml=s"      => \$cmml,
	   "openmath|om=s"             => \$om,
	   "XMath=s"                   => \$xmath,

	   "noparse"   => \$noparse,

	   "preload=s" => \@preload,
	   "includestyles"=> \$includestyles,
	   "path=s"    => \@paths,
	   "quiet"     => sub { $verbosity--; },
	   "verbose"   => sub { $verbosity++; },
	   "strict"    => \$strict,
	   "VERSION"   => \$showversion,
	   "debug=s"   => sub { eval "\$LaTeXML::$_[1]::DEBUG=1; "; },
	   "documentid=s" => \$documentid,
	   "help"      => \$help,
	  ) or pod2usage(-message => $identity, -exitval=>1, -verbose=>0, -output=>\*STDERR);
pod2usage(-message=>$identity, -exitval=>1, -verbose=>2, -output=>\*STDOUT) if $help;
if($showversion){ print STDERR "$identity\n"; exit(1); }
pod2usage(-message=>"$identity\nMissing input TeX file", 
	  -exitval=>1, -verbose=>0,-output=>\*STDERR) unless @ARGV;

binmode(STDERR,":utf8");
print STDERR "$identity\n" unless $verbosity < 0;

#======================================================================
# TeX Source
#======================================================================
# First read and digest whatever we're given.
my $tex = join(' ',@ARGV);
if($tex eq '-'){
  my $content;
  { local $/ = undef; $tex = <>; }}

# my $texdoc = <<EODoc;
# \\documentclass{article}
# \\begin{document}
# \\[ $tex \\]
# \\end{document}
# EODoc
my $texdoc = <<EODoc;
\\newcounter{equation}
\\newcounter{Unequation}
\\[ $tex \\]
EODoc

# NOTE:
#   Should I do something to verify that there is ONLY one Math node ?
#   Eg: cmdline  a + b $ \badmacros $ c + d
#
#   What about alignment environments? 
#     Should it be possible to give eqnarray or similar?
#     and if so, will they give multiple math nodes?

#======================================================================
# Digest the TeX
#======================================================================
@paths = map(pathname_canonical($_),@paths);
if(my @baddirs = grep(! -d $_, @paths)){
  warn "$identity: these path directories do not exist: ".join(', ',@baddirs)."\n"; }

my $latexml= LaTeXML->new(preload=>['LaTeX.pool',@preload], searchpaths=>[@paths],
			  verbosity=>$verbosity, strict=>$strict,
			  includeComments=>0,includeStyles=>$includestyles,
			  documentid=>$documentid,
			  nomathparse=>$noparse);

# Digest and convert to LaTeXML's XML
my $doc = LaTeXML::Post::Document->new($latexml->convertString($texdoc),
				      nocache=>1);

#======================================================================
# Postprocess to convert the math to whatever desired forms.
#======================================================================
# Since we can't easily find & extract all the various formats at once,
# let's just process each one separately.

our %OPTIONS = (verbosity=>$verbosity||0);

if($mathimage){
  if($mathimage eq '-'){
    die "I dont really want to write the image to STDOUT, sorry!"; }
  $mathimage =~ s/\.(png|gif|jpg|jpeg)$//;
  my $imagetype = $1 || 'png';
#  require 'LaTeXML/Post/MathImages.pm';
  my($post) = LaTeXML::Post::ProcessChain($doc,
      DirectMathImages->new(magnification=>$mag,
			    imagename=>$mathimage, imagetype=>$imagetype,
			    %OPTIONS));
}

if($pmml){
  require 'LaTeXML/Post/MathML.pm';
  my($post) = LaTeXML::Post::ProcessChain($doc,
      LaTeXML::Post::MathML::Presentation->new(
          (defined $linelength ? (linelength=>$linelength):()),
	   %OPTIONS));
  outputXML($post->findnode('//m:math'), $pmml); }

if($cmml){
  require 'LaTeXML/Post/MathML.pm';
  my($post) = LaTeXML::Post::ProcessChain($doc,
      LaTeXML::Post::MathML::Content->new(%OPTIONS));
  outputXML($post->findnode('//m:math'), $cmml); }

if($om){
  require 'LaTeXML/Post/OpenMath.pm';
  my($post) = LaTeXML::Post::ProcessChain($doc,
      LaTeXML::Post::OpenMath->new(%OPTIONS));
  outputXML($post->findnode('//om:OMOBJ'), $om); }

if($xmath){
  # extract the xmath
  my($post) = LaTeXML::Post::ProcessChain($doc);
  outputXML($post->findnode('//ltx:XMath'), $xmath); }

#======================================================================
# Helpers
#======================================================================

sub outputXML {
  my($xml,$destination)=@_;
  # Need to move the node to a new document to set up namespaces
  my $newdoc = XML::LibXML::Document->new("1.0","UTF-8");
  $newdoc->setDocumentElement($xml);
  my $serialized = $newdoc->toString(1);
  if($destination eq '-'){
    print $serialized; }
  else {
    $destination = pathname_canonical($destination);
    if(my $dir =pathname_directory($destination)){
      pathname_mkdir($dir) or die "Couldn't create destination directory $dir: $!"; }
    open(OUT,">",$destination) or die "Couldn't open output file $destination: $!";
    print OUT $serialized;
    close(OUT); }}

#======================================================================
# Variant of MathImages to write directly to destination
#======================================================================
package DirectMathImages;
use base qw(LaTeXML::Post::MathImages);

our $counter;
sub desiredResourcePathname {
  my($self,$doc,$node,$source,$type)=@_;
  my $name = $$self{imagename};
  if($counter){			# Shouldn't get multiple images, but just in case...
    $name.$counter++.'.'.$type; }
  else {
    $counter++;
    $name.'.'.$type; }}

#**********************************************************************
__END__

=head1 NAME

C<latexmlmath> - transforms a TeX/LaTeX math expression into various formats.

=head1 SYNOPSIS

latexml [options] texmath

 Options:
 --mathimage=file           converts to image in file
 --magnification=mag        specifies magnification factor
 --presentationmathml=file  converts to Presentation MathML
 --pmml=file                alias for --presentationmathml
 --linelength=n             do linewrapping of pMML
 --contentmathml=file       convert to Content MathML
 --cmml=file                alias for --contentmathml
 --openmath=file            convert to OpenMath
 --om=file                  alias for --openmath
 --XMath=file               convert to LaTeXML's internal format
 --noparse                  disables parsing of math
                            (not useful for cMML or openmath)
 --preload=file             loads a style file.
 --includestyles            allows processing raw *.sty files
                            (normally it avoids this)
 --path=dir                 adds a search path for style files.
 --quiet                    reduces verbosity (can be repeated)
 --verbose                  increases verbosity (can be repeated)
 --strict                   be more strict about errors.
 --documentid=id            assign an id to the document root.
 --debug=package            enables debugging output for the
                            named package
 --VERSION                  show version number and exit.
 --help                     shows this help message.

If texmath is '-', latexml reads the TeX from standard input.
If any of the output files are '-', the result is printed on standard output.

=head1 OPTIONS AND ARGUMENTS

=head2 Conversion Options

These options specify what formats the math should be converted to.
In each case, the destination file is given.  Except for
mathimage, the file can be given as '-', in which case the
result is printed to standard output.

=over 4

=item C<--mathimage>=I<file>

Requests conversion to png images.

=item C<--magnification=>I<factor>

Specifies the magnification used for math image. Default is 1.75.

=item C<--presentationmathml>=I<file>

Requests conversion to Presentation MathML.

=item C<--linelength>I<=number>

(Experimental) Line-breaks the generated Presentation
MathML so that it is no longer than I<number> `characters'.

=item C<--contentmathml>=I<file>

Requests conversion to Content MathML.
B<Note> that this conversion is only partially implemented.

=item C<--openmath>=I<file>

Requests conversion to OpenMath.
B<Note> that this conversion is only partially implemented.

=item C<--XMath>=I<file>

Requests convertion to LaTeXML's internal format.

=back

=head1 Other Options

=over 4

=item C<--preload>=I<module>

Requests the loading of an optional module or package.  This may be useful if the TeX code
does not specificly require the module (eg. through input or usepackage).
For example, use C<--preload=LaTeX.pool> to force LaTeX mode.

=item C<--includestyles>

This optional allows processing of style files (files with extensions C<sty>,
C<cls>, C<clo>, C<cnf>).  By default, these files are ignored  unless a latexml
implementation of them is found (with an extension of C<ltxml>).

These style files generally fall into two classes:  Those
that merely affect document style are ignorable in the XML.
Others define new markup and document structure, often using
deeper LaTeX macros to achieve their ends.  Although the omission
will lead to other errors (missing macro definitions), it is
unlikely that processing the TeX code in the style file will
lead to a correct document.

=item C<--path>=I<dir>

Add I<dir> to the search paths used when searching for files, modules, style files, etc;
somewhat like TEXINPUTS.  This option can be repeated.

=item C<--documentid>=I<id>

Assigns an ID to the root element of the XML document.  This ID is generally
inherited as the prefix of ID's on all other elements within the document.
This is useful when constructing a site of multiple documents so that
all nodes have unique IDs.

=item C<--quiet>

Reduces the verbosity of output during processing, used twice is pretty silent.

=item C<--verbose>

Increases the verbosity of output during processing, used twice is pretty chatty.
Can be useful for getting more details when errors occur.

=item C<--strict>

Specifies a strict processing mode. By default, undefined control sequences and
invalid document constructs (that violate the DTD) give warning messages, but attempt
to continue processing.  Using --strict makes them generate fatal errors.

=item C<--VERSION>

Shows the version number of the LaTeXML package..

=item C<--debug>=I<package>

Enables debugging output for the named package. The package is given without the leading LaTeXML::.

=item C<--help>

Shows this help message.

=back

=head1 BUGS

This program runs much slower than would seem justified.
This is a result of the relatively slow initialization
including loading TeX and LaTeX macros and the schema.
Normally, this cost would be ammortized over large documents,
whereas, in this case, we're processing a single math expression.

=head1 SEE ALSO

L<latexml>, L<latexmlpost>, L<LaTeXML>

=cut
#**********************************************************************

