=begin header
Wrapper Library for lv.o

    $Author: igarashi $
    $Date: 2000/06/08 17:34:14 $
=end

require 'lv.o'

class IChar
end

class IString
  case $KCODE
  when "EUC"
    def to_s
      LV.encode(self, LV::EUC_JP)
    end
  when "SJIS"
    def to_s
      LV.encode(self, LV::SHIFT_JIS)
    end
  else
    def to_s
      LV.encode(self, LV::ISO_2022_JP)
    end
  end
  def inspect
    "\"#{to_s}\""
  end
end

class LV
  # aliases (for backward compatibility)
  EUC_KR = EUC_KOREA
  EUC_JP = EUC_JAPAN
  EUC_TW = EUC_TAIWAN
  EUC_CN = EUC_CHINA

  # mapping from CES name to id
  CESName2ID = {
    "autoselect" => AUTOSELECT,
    "utf-7" => UTF_7,
    "hz-gb" => HZ_GB,
    "euc-korea" => EUC_KOREA,
    "euc-japan" => EUC_JAPAN,
    "euc-taiwan" => EUC_TAIWAN,
    "euc-china" => EUC_CHINA,
    "big5" => BIG_FIVE,
    "shift-jis" => SHIFT_JIS,
    "utf-8" => UTF_8,
    "iso-8859-1" => ISO_8859_1,
    "iso-8859-2" => ISO_8859_2,
    "iso-8859-3" => ISO_8859_3,
    "iso-8859-4" => ISO_8859_4,
    "iso-8859-5" => ISO_8859_5,
    "iso-8859-6" => ISO_8859_6,
    "iso-8859-7" => ISO_8859_7,
    "iso-8859-8" => ISO_8859_8,
    "iso-8859-9" => ISO_8859_9,
    "iso-2022-cn" => ISO_2022_CN,
    "iso-2022-jp" => ISO_2022_JP,
    "iso-2022-kr" => ISO_2022_KR,
    "raw" => RAW,
  }.freeze

  def initialize(from_ces, to_ces)
    @from_ces =
      case from_ces
      when String
	CESName2ID[from_ces]
      else
	from_ces
      end
    @to_ces =
      case to_ces
      when String
	CESName2ID[to_ces]
      else
	to_ces
      end
    if @from_ces.nil? or @to_ces.nil?
      raise ArgumentError, "not supported CES"
    end
  end

  def convert(str)
    LV.encode(LV.decode(str, @from_ces), @to_ces)
  end

  def flush
    ""
  end

  def reset
    self
  end
end

class << LV
  def convert(str, from_ces, to_ces)
    new(from_ces, to_ces).convert(str)
  end
  alias_method(:conv, :convert)
end


=begin
Caution: Following classes are defined experimentally.
=end

class LV

  class Reader
    def initialize(stream, from_ces)
      @stream = stream
      @from_ces = from_ces
    end
    public
    def gets
      mbs = @stream.gets
      if mbs.nil?
	nil
      else
	LV.decode(mbs, @from_ces)
      end
    end
  end

  class Writer
    def initialize(stream, to_ces)
      @stream = stream
      @to_ces = to_ces
    end
    public
    def puts(is)
      mbs = LV.encode(is, @to_ces)
      @stream.puts(mbs)
    end
  end

end

