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

class MathMLWrapper

  # Mathml library name
  MATHML_NAME= "mathml"

  # $LOAD_PATH/MACRO_PATH/* files are parsed as TeX macro
  MACRO_PATH = "#{MATHML_NAME}/macro"

  @@macro_input_flag = false

  def initialize
    @load_error_flag = false
    begin
      require MATHML_NAME
      if !@@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|
                io.each{ |line|
                  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"
                  end
                }
              }
            end
          }
        }
      end
    rescue LoadError
      @load_error_flag = true
    end
  end
  def parse(formula, block=false)
    return formula if @load_error_flag
    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
