#!/usr/bin/env ruby

require 'commit'

SITE = 'pm'

# math, displaymath, eqnarray, equation, \[, $, \(
MATHENV =
  [
   [ '$', '$' ],
   [ '\[', '\]' ],
   [ '\(', '\)' ],
   [ '\begin{math', '\end{math' ],
   [ '\begin{displaymath', '\end{displaymath' ],
   [ '\begin{eqnarray', '\end{eqnarray' ],
   [ '\begin{equation', '\end{equation' ],
   [ '\begin{aligned', '\end{aligned' ],
   [ '\begin{alignat', '\end{alignat' ],
   [ '\begin{align', '\end{align' ],
   [ '\begin{falign', '\end{falign' ],
   [ '\begin{xalignat', '\end{xalignat' ],
   [ '\begin{xxalignat', '\end{xxalignat' ],
  ]

@com = Commit.new

def add_tex(tex)
  title = tex.dup
  title.gsub!(/^.*\//, '')
  title.sub!(/\.tex$/, '')
  print "#{title}\n"

  started = false
  cont = ''
  File.open(tex) do |ifile|
    ifile.each do |line|
      line.sub!(/%.*/, '')

      started = true if line =~ /\\begin\{document/
      next if !started

      next if line =~ /^\s*$/
      next if line =~ /newcommand/

      line.chomp!

      cont += "#{line} "
    end
  end

#  print "#{cont}\n"
  MATHENV.each do |math|
    while true
      b = cont.index(math[0])
      break if !b
      while (cont[b-1].chr == '\\' && cont[b-2].chr != '\\')
        b = cont.index(math[0], b+1)
        break if !b
      end
      break if !b
      s = b+math[0].size

      e = cont.index(math[1], s)
      break if !e
      while (cont[e-1].chr == '\\' && cont[e-2].chr != '\\')
        e = cont.index(math[1], e+1)
      end

      f = cont[s...e]
      f.sub!(/^\*/, '')
      f.sub!(/^\}/, '')
      cont = cont[0...b] + cont[e+math[1].size..-1]

#      print "#{f}\n"
      f.split('\\\\').each do |m|
        @com.add(m, SITE, title)
      end
    end
  end
end

def add_dir(d)
  Dir.open(d) do |dir|
    dir.each do |e|
      next if e =~ /^\./
      e = "#{d}/#{e}"
      if (e =~ /\.tex$/)
        add_tex(e)
      elsif (File.directory?(e))
        add_dir(e)
      end
    end
  end
end

t = ARGV[0]
if (t =~ /\.tex$/)
  add_tex(t)
elsif (File.directory?(t))
  add_dir(t)
else
  print "#{t}: ???\n"
end

@com.close
