#! /usr/bin/perl

# Copyright (C) 2009 Matous Jan Fialka, <http://mjf.cz/>
# Released under the terms of The MIT License

# Note: This code snippet will be part of the WIT project soon.
# Todo: Cope with escaped EOLs.

use strict;
use warnings;

use Data::Dumper;

sub parse
{
        my %h = ();
        my $r = \%h;

        sub strip
        {
                $_ = shift;

                s/^\s*//;
                s/\s*$//;
                s/\\(.?)$/$1?$1:' '/e;
                s/\\(.)/$1/g;

                $_;
        }

        while (<>) {

                ($_) = /^((?:[^\\#]++|\\.)*+)/;

                next if /^\s*$/;

                if (/^\s*+\[((?:[^\\\]]++|\\.)*+)\]\s*+$/o) {

                        $r = \%h;

                        foreach (map {/((?:[^\\,]++|\\.)++)/go} $1) {
                                $r = $r->{strip $_} //= {};
                        }

                        next;
                }
                if (/^\s*+((?:[^\\=]++|\\.)++)=(.*)/o) {

                        my $v = $2;

                        for (map {/(?:[^\\,]++|\\.)++/go} $1) {

                                my $o = strip $_;

                                for (map {/(?:[^\\,]++|\\.)++/go} $v) {
                                        push @{$r->{_}{$o}}, strip $_;
                                }
                        }

                        next;
                }

                return \%h, $., ($_) = /^(.*)$/;
        }

        \%h, 0, undef;
}

print Dumper parse;
