# This class is MathML module wrapper.
# If MathML module can not be loaded, methods in this module return
# raw argument without modification.
require 'fileutils'

class MathMLWrapper

  # Mathml library name
  MATHML_NAME = [ "mathml", "math_ml" ]

  # $LOAD_PATH/MATHML_NAME/MACRO_REL_PATH/* files are parsed as TeX macro
  MACRO_REL_PATH = "macro"

  @@mathml_required = false
  @@macro_input_flag = false
  @@macro_path = ''

  def initialize

    err_count = 0
    if !@@mathml_required
      MATHML_NAME.each{ |ml|
        begin
          require ml
          @@macro_path = File.join(ml, MACRO_REL_PATH)
        rescue LoadError
          err_count = err_count + 1
        end
      }
      if err_count < MATHML_NAME.size
        @@mathml_required = true
      else
        raise LoadError, 
          "  Error: \"#{MATHML_NAME.join('" or "')}\" library is not found\n" +
          "         in $LOAD_PATH=[#{$LOAD_PATH.join(',')}]\n\n"
      end
    end

    if (@@mathml_required && !@@macro_input_flag)
      @@mathml_formula_macro = MathML::LaTeX::Parser.new
      @@macro_input_flag = true
      $LOAD_PATH.each{ |lpath|
        macro_files = Dir::glob(File.join(lpath, @@macro_path, "*"))
        macro_files.each{ |mfile|
          if File.file?(mfile)
            File.open(mfile, "r" ) { |io|
              if $DEBUG_RDOC 
                puts \
                  "\n##### Debug messages about \"#{__FILE__}\" #####", 
                  "  \"#{mfile}\" is loading as a TeX macro file.", 
                  "  Following macros have been included."
              end
              io.each{ |line|
                line.chomp!
                macroerrormsg = nil
                begin
                  @@mathml_formula_macro.macro.parse(line)
                rescue MathML::LaTeX::ParseError
                  macroerrormsg = $!.to_s
                rescue
                  macroerrormsg = $!.to_s
                end
                if macroerrormsg
                  $stderr.puts "Warning: in #{mfile}, following TeX macro causes #{macroerrormsg.to_s}\n\n",
                  "    #{line}\n\n"
                else
                  if $DEBUG_RDOC && !(line.empty?) && !(line =~ /\s*\%/)
                    puts "    #{line}"
                  end
                end
              }
            }
          end
        }
      }
    end

  end
  def parse(formula, block=false)
    return formula if !@@mathml_required
    mathml_formula = @@mathml_formula_macro
    begin
      mathml_formula_str = mathml_formula.parse(formula, block).to_s
    rescue MathML::LaTeX::ParseError
      return formula, 1
    rescue
      return formula, 1
    end
    return mathml_formula_str, 0
  end
end
