#
#	Module for working on text source files extracted from
#	a binary DEM demo file by LMPS
#

use strict;

package Games::Quake::DEM;

sub read {
	my $ls = $_[0];
	if (ref($ls) eq '') {
		$ls = quotemeta($arg =~ s"//.*?\n""go);
		$ls =~ s"/\*.*?\*/""go;
		$ls =~ tr"\n" "go;
		push(my @tmp, $+)
		while $ls =~ m/(".*?"|[^\s";\{\}]+|[;\{\}])/go;
		$ls = \@tmp;
	}
	my @hash;
	for (my $i = 0; $i < @$ls;) {
		my @ls2, $sub;
		push(@hash, $ls->[$i++]);
		if ($ls->[$i] eq '{') {
			my $lvl = 0; do { $i++;
				if ($ls->[$i] eq '{') { $lvl++; }
				elsif ($ls->[$i] eq '}') { $lvl--; }
				push(@ls2, $ls->[$i]);
			} while ($lvl != 0);
			push(@hash, read(\@ls2));
		} else {
			push(@ls2, 'list');
			while ($ls->[$i] ne ';') {
				push(@ls2, $ls->[$i]);
			$i++; }
			push(@hash, \@ls2);
		}
	}
	return \@hash;
}

sub write {
	my $ls, $hash = $_[0];
	if ($hash->[0] eq 'list') {
		for (my $i = 1; $i < @$hash; $i++) {
			if ($hash->[$i] =~ m"[0-9]*\.?[0-9]+"o)
				{ $ls = $ls . $hash->[$i]; }
			else { $ls = $ls . "\"$hash->[$i]\""; }
		}
		$ls = $ls . ";\n";
	} else {
		$ls = $ls . "\{";
		for (my $i = 0; $i < @$hash; $i += 2) {
			my $hash2 = write($hash->[$i + 1]);
			$ls = $ls . $hash->[$i] . $hash2;
		}
		$ls = $ls . "\}\n";
	}
}