require 'find'
$JCODE = 'u'

class Extractor
  def initialize
    @lang1 = Hash.new
    @dict = []
    @counter1 = 0 
    @counter2 = 0 
  end

  def add_file_lang1(file)
    f = File.open(file)
    while !f.eof?
      b = f.readline
      if b.index("msgid")
        msgid = b.scan(/"(.*)"/)[0]
        trans = f.readline.scan(/"(.*)"/)
        if trans.size > 0
          unless msgid[0] == '' || trans[0][0] == ''        
            @lang1[msgid[0]] = trans[0][0]
            @counter1 += 1
          end
        end
      end
    end
  end

  def add_file_lang2(file)
    f = File.open(file)
    while !f.eof?
      b = f.readline
      if b.index("msgid")
        msgid = b.scan(/"(.*)"/)[0]
        trans = f.readline.scan(/"(.*)"/)
        if trans.size > 0
          unless msgid[0] == '' || trans[0][0] == ''        
            if @lang1[msgid[0]] && trans[0][0] =~ /[⾰-⾿]/
              @dict << [@lang1[msgid[0]], trans[0][0]]
            end
            @counter2 += 1
          end
        end
      end
    end
  end

  def dictionary
    @dict
  end

  def found_words
    [@counter1, @counter2]
  end
end

def traverse(dir)
  out = []
  Find.find(dir) do |path|
    if FileTest.directory?(path)
      if File.basename(path)[0] == ?.
        Find.prune       # Don't look any further into this directory.
      else
        next
      end
    else
      if path =~ /\.po$/
        out << path
      end
    end
  end
  return out
end

lang1 = ARGV[0]
lang2 = ARGV[1]

extract = Extractor.new
traverse(lang1).each {|f| extract.add_file_lang1(f)}
traverse(lang2).each {|f| extract.add_file_lang2(f)}
$stderr.puts "Stats: lang1 strings: #{extract.found_words[0]}, lang2 strings: #{extract.found_words[1]}, matching strings: #{extract.dictionary.size}"
extract.dictionary.each {|words| puts "#{words[0]}\t#{words[1]}"}

