package Magnus;

sub new {
    my	$header = shift;
    my	$self = {};
    my	$source;
    my	$line;

    $self->{'sourceDeleted'} = {};
    $self->{'file'} = shift;
    if ( ! open( FILE, $self->{'file'} ) ) {
	$@ = $!;
	return undef;
    }
    while ( <FILE> ) {
	$source = $_;
	while ( /\\$/ ) {	# continuation
	    $line = <FILE>;
	    $_ = $` . $line;
	    $source .= $line;
	    last if $_ eq $`;	# in case of EOF
	}
	push( @{$self->{'source'}}, $source );
	next if /^\s*$/;
	next if /^#/;
	chomp( $_ );
	( $var, $val ) = /(\w+)\s+(.*)/;
	$var = "\L$var";
	if ( $var eq 'init' ) {
	    push( @{$self->{'inits'}}, $val );
	    push( @{$self->{'initIndex'}}, $#{$self->{'source'}} );
	} else {
	    warn "Duplicate $var: $self->{'file'}: $.\n"
		if $self->{'vars'}->{$var};
	    $self->{'vars'}->{$var} = $val;
	    $self->{'index'}->{"\L$var"} = $#{$self->{'source'}};
	}
    }
    close( FILE );
    bless $self;
}

sub set {
    my	$self = shift;
    my	$var = shift;
    my	$val = shift;
    my	$index = defined( $self->{'vars'}->{"\L$var"} ) ?
	$self->{'index'}->{"\L$var"} : scalar( @{$self->{'source'}} );

    $self->{'vars'}->{"\L$var"} = $val;
    $self->{'source'}->[$index] = "$var $val\n";
    $self->{'index'}->{"\L$var"} = $index;
    $self->{'modified'} = 1;
}

sub value {
    my	$self = shift;
    my	$var = shift;

    return $self->{'vars'}->{"\L$var"};
}

sub deleteVar {
    my	$self = shift;
    my	$var = shift;

    $self->{'sourceDeleted'}->{$self->{'index'}->{"\L$var"}} = 1;
    $self->{'modified'} = 1;
}

sub numInits {
    my	$self = shift;

    return scalar( @{$self->{'inits'}} );
}

sub getInit {
    my	$self = shift;
    my	$index = shift;

    return $self->{'inits'}->[$index];
}

sub addInit {
    my	$self = shift;
    my	$init = shift;

    push( @{$self->{'inits'}}, $init );
    push( @{$self->{'source'}}, "Init $init\n" );
    push( @{$self->{'initIndex'}}, $#{$self->{'source'}} );
    $self->{'modified'} = 1;
}

sub deleteInit {
    my	$self = shift;
    my	$index = shift;

    $self->{'sourceDeleted'}->{$self->{'initIndex'}->[$index]} = 1;
    $self->{'modified'} = 1;
}

sub flush {
    my	$self = shift;

    if ( $self->{'modified'} ) {
	my	$i;

	open( FILE, ">$self->{'file'}" ) ||
	    die "Can't write to $self->{'file'}: $!\n";
	for ( $i = 0 ; $i < scalar( @{$self->{'source'}} ) ; ++$i ) {
	    print FILE $self->{'source'}->[$i]
		unless $self->{'sourceDeleted'}->{$i};
	}
	close( FILE );
    }
    $self->{'modified'} = 0;
}

1;
