
# Parse and write windows ini format.
#
# See http://blog.b-shock.co.jp/pooza/2007/07/inifilerb.html
#     modify by katoy

class Inifile

  VERSION = '0.0.1'

  #
  # parse ini format.
  #
  def parse_file(path)
    settings = {}
    File.open(path) do |file|
      settings = parse_lines(file.read)
    end
    settings
  end

  #
  # parse array of line.
  #
  def parse_lines(lines)
    settings = {}
    section = nil
    lines.each_with_index do |line, index|
      if /^;.*$/ =~ line
        # comment line
      elsif /^[ \t]*\[(.*)\] *$/ =~ line
        section = $1
      elsif /^(.*)=(.*)$/ =~ line
        key = $1.strip
        value = $2.strip
        settings[section] ||= []
        settings[section].push(key.to_sym => value)
      elsif /^[ \t]*$/ =~ line
        # empty line
      else
        raise "Syntex Error: line #{index + 1}: '#{line}\'"
      end
    end
    settings
  end

  #
  # write ini format.
  #
  def write(settings, file = $stdout)
    lines = generate_lines(settings)
    lines.each {|line| file.puts line }
  end

  #
  # write ini format.
  #
  def generate_lines(settings, file = $stdout)
    lines = []
    settings.each_pair do |section, confs|
      lines << "[#{section}]"
      confs.each do |conf|   
        conf.to_a.each do |line|        
          lines << "  #{line[0]} = #{line[1]}"
        end
      end
      lines << ""
    end
    lines
  end

end
