package Plotter;

sub new {
    use Tk;
    shift;
    my $height = shift;
    my $width = shift;

    my $win = MainWindow->new;
    my $c = $win->Canvas(-height => $height, -width => $width);
    $c->pack();

    return bless {
	'window' => $win,
	'canvas' => $c,
	'plots' => {},
	'height' => $height,
	'width' => $width,
    }
}

sub addPlot {
    my $self = shift;
    my $plotname = shift;
    my $mode = shift;

    my $myplots = $self->{plots};
#    ${$myplots}{$plotname} = new Plot ($plotname, $self);
    ${$myplots}{$plotname} = my $tp = Plot->new($plotname, $self, $mode);
}

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

    ${$self->{plots}}{$plot}->add($value);
}

sub update {
    my $self = shift;
    $self->{canvas}->update()
}

1;

package Plot;

sub new {
    shift;
    my $name = shift;
    my $plotter = shift;
    my $mode = shift;
    my $vals = [];
    return bless {
	'name' => $name,
	'plotter' => $plotter,
	'values' => $vals,
	'mode' => $mode
    };
}

sub add {
    my $self = shift;
    my $v = shift;

    $v = 1-$v;

    if($self->{mode} == 1){
	if($#{$self->{values}} > ($self->{plotter}->{width}/2)){
	    $idx = $self->{idx};
	    $self->{plotter}->{canvas}->delete(${$self->{values}}[$idx]);
	    ${$self->{values}}[$idx] = $self->{plotter}->{canvas}->create(oval, 
									  2+$idx*2,
									  ($v*$self->{plotter}->{height}),
									  4+$idx*2,
									  ($v*$self->{plotter}->{height})+2);
    $self->{idx}++;
    if($self->{idx} > ($#{$self->{values}})){
	$self->{idx} = 0;
    }

		   }
	else{
	    push(@{$self->{values}}, 
		 $self->{plotter}->{canvas}->create(oval, 
						    2+$#{$self->{values}}*2,
						    ($v*$self->{plotter}->{height}),
						    4+$#{$self->{values}}*2,
						    ($v*$self->{plotter}->{height})+2)
	     );

	}
    }
    elsif($self->{mode} == 0){
	if($#{$self->{values}} > ($self->{plotter}->{width}/2)){
	    my $d = shift @{$self->{values}};
	    $self->{plotter}->{canvas}->delete($d);
	    my $p;
	    foreach $p (@{$self->{values}}){
		$self->{plotter}->{canvas}->move($p, -2, 0);
	    }
	}
	push(@{$self->{values}}, 
	     $self->{plotter}->{canvas}->create(oval, 
						2+$#{$self->{values}}*2,
						($v*$self->{plotter}->{height}),
						4+$#{$self->{values}}*2,
						($v*$self->{plotter}->{height})+2)
	     );
    }
}
1;
