#!ruby -Ku
# -*- coding: utf-8 -*-
require "GeoService"
require "rbdams"
require "./libgeoanalyze.rb"
include DAMS

# ジオコーダ初期化
#SPAT_DATA_DIR = "/var/www/geoparser" # File.dirname(__FILE__) + "/spat_files"
#dams_init(SPAT_DATA_DIR + "/all_latlon", SPAT_DATA_DIR + "/itaiji.txt")
dams_init("/opt/spat/spat_data/bindata/wgs1984/all_latlon", "/usr/local/etc/itaiji.txt")
dams_set_exact_match_level(5)

# 地名語パーサ初期化
service = GeoService.new("GeoParser")


# コマンドラインパラメータの取得（処理モード）
mode = 'MeCab'
if ARGV.size > 0
  if ARGV[0] == '-h' || ARGV[0] == '--help'
    STDERR.printf("使い方: ruby analyze.rb [mode]\n\n入出力は標準入出力に対して行います。\nmodeには MeCab, JSON, SPA の3種類が指定できます。省略した場合には MeCab モードになります。\n")
    exit 0
  end
  mode = ARGV[0]
end

# メイン
sequence = GeoSequence.new({'threshold'=>0})
sequence.flush  # バッファをクリア

putc('[') if mode == 'JSON' # JSON モードの場合だけ、先頭と最後に [] が必要
output_length = 0
while (line = STDIN.gets)
  nodes = service.parseNode(line)
  sequence = sequence.analyze(nodes, service)
  result = sequence.drawResults(mode)
  if mode == 'JSON' && output_length > 0 && result.length > 0
    STDOUT.print ",\n"
    output_length += 2
  end
  STDOUT.print result
  output_length += result.length
end
sequence.flush
result = sequence.drawResults(mode)
if mode == 'JSON' && output_length > 0 && result.length > 0
  STDOUT.print ",\n"
  output_length += 2
end
STDOUT.print result

putc(']') if mode == 'JSON'
