#! /usr/bin/env ruby
#
# migemo - a tool for Japanese incremental search.
#
# Copyright (C) 2001 Satoru Takabayashi <satoru@namazu.org>
#     All rights reserved.
#     This is free software with ABSOLUTELY NO WARRANTY.
#
# You can redistribute it and/or modify it under the terms of 
# the GNU General Public License version 2.
#

$KCODE = "e"

require 'migemo'
require 'getoptlong'

def print_usage
  print "\
Usage: migemo [OPTION] [DICT]
  -h, --help             Display this help and exit
  -u, --user-dict=DICT   Use DICT as a user dictionary.
  -r, --regex-dict=DICT  Use DICT as a regex dictionary.
  -O, --optimize=LEVEL   Optimize output regular expressions (0-3). [3]
  -t, --type=TYPE        Set regex type to TYPE ([ruby], perl, emacs, egrep)
  -i, --insert=STRING    Insert STRING to each character.
  -s, --separator=STRING Insert String to each regular expression.
  -n, --nocache		 Don't use caches.
"
end

def parse_options
  options = Hash.new
  options['optimize'] = 3

  parser = GetoptLong.new
  parser.set_options(['--help', '-h',           GetoptLong::NO_ARGUMENT],
		     ['--regex-dict', '-r',     GetoptLong::REQUIRED_ARGUMENT],
		     ['--user-dict', '-u',      GetoptLong::REQUIRED_ARGUMENT],
		     ['--optimize', '-O',       GetoptLong::REQUIRED_ARGUMENT],
		     ['--type', '-t',           GetoptLong::REQUIRED_ARGUMENT],
		     ['--insert', '-i',		GetoptLong::REQUIRED_ARGUMENT],
		     ['--separator', '-s',	GetoptLong::REQUIRED_ARGUMENT],
		     ['--nocache', '-n',	GetoptLong::NO_ARGUMENT])

  parser.each_option do |name, arg|
    options[name.sub /^--/, ""] = arg
  end

  if options['help']
    print_usage
    exit 1
  end

  if ARGV.length != 1
    print_usage
    exit 1
  end

  return options
end

def main
  options = parse_options
  static_dict = MigemoStaticDict.new(ARGV[0])

  if options['nocache'] == nil && File.readable?(ARGV[0] + ".cache")
    dict_cache = MigemoDictCache.new(ARGV[0] + ".cache")
  end

  if options['user-dict'] != nil 
    if File.readable?(options['user-dict'])
      user_dict = MigemoUserDict.new(options['user-dict'])
    else
      raise "user dictionary not found: #{options['user-dict']}"
    end
  end

  if options['regex-dict'] != nil 
    if File.readable?(options['regex-dict'])
      regex_dict = MigemoRegexDict.new(options['regex-dict'])
    else
      raise "regex dictionary not found: #{options['regex-dict']}"
    end
  end

  ARGV.shift

  $stdout.sync = true
  while line = gets
    pattern = line.chomp
    migemo = Migemo.new(static_dict, pattern)
    migemo.user_dict = user_dict if user_dict
    migemo.regex_dict = regex_dict if regex_dict
    migemo.dict_cache = dict_cache if dict_cache
    migemo.type = options['type'] if options['type']
    migemo.optimization = options['optimize'].to_i if options['optimize']
    migemo.insertion = options['insert'] if options['insert']
    puts migemo.regex
    puts options['separator'] if options['separator']
  end
end

main
