#!/usr/bin/perl
use Tk;
use Tk::PlotDataset;
use Tk::LineGraphDataset;
use Math::GSL::SF qw/:all/;
use strict;

my ( %sets, $graph );
my $window = MainWindow->new( -title => 'Math::GSL Plot', );
my @popo = ("gsl_sf_bessel_J0", "gsl_sf_bessel_J1", "gsl_sf_bessel_Y0", "gsl_sf_bessel_Y1");

for my $n (0..3) {
 my $del;
 $window->Button(
     -text    => $popo[$n],
     -command => sub {
         region($popo[$n]);
         $del->configure( -state => "normal" );
     }
 )->pack;
 $del = $window->Button(
     -text    => "Remove " . $popo[$n],
     -state   => "disabled",
     -command => sub {
         delete_set($popo[$n]);
         $del->configure( -state => "disabled" );
     }
 )->pack;
}


$window->Button( -text => "test", -command => [ \&region, "test", $window ] )
  ->pack;

sub region {
    my $name = shift;
    if ($graph) { $graph->packForget(); }

    my @region = map { $_ / 10 } ( -400 .. -1, 0, 1 .. 400 );
    my @region2 = map { $_ / 10 } ( 1 .. 400 );
    my %functions = (
        "gsl_sf_bessel_J0" => \&sf_bessel_J0,
        "gsl_sf_bessel_J1" => \&sf_bessel_J1,
        "gsl_sf_bessel_Y0" => \&sf_bessel_Y0,
        "gsl_sf_bessel_Y1" => \&sf_bessel_Y1,
        "test"             => \&test,
    );
    my @data1;
    if ($name) {
        if ( $name =~ /(Y1|Y0)$/ ) {
            @data1 = map { $functions{$name}->($_) } (@region2);
        }
        else {
            @data1 = map { $functions{$name}->($_) } (@region);
        }

        my $dataset1 = LineGraphDataset->new(
            -name      => $name,
            -plottitle => [$name],
            -xData     => \@region,
            -yData     => \@data1,
            -yAxis     => 'Y',

            #     -color => 'red'
        );
        $sets{$name} = $dataset1;
    }
    $graph = $window->PlotDataset(
        -width      => 500,
        -height     => 500,
        -background => 'snow'
    )->pack( -fill => 'both', -expand => 1 );

    my @datasets = values %sets;
    $graph->addDatasets(@datasets);
    $graph->plot;
}

sub delete_set {
    my $name = shift;
    delete $sets{$name};
    &region;
}

sub sf_bessel_J0 {
    return gsl_sf_bessel_J0( $_[0] );
}

sub sf_bessel_J1 {
    return gsl_sf_bessel_J1( $_[0] );
}

sub sf_bessel_Y0 {
    return gsl_sf_bessel_Y0( $_[0] );
}

sub sf_bessel_Y1 {
    return gsl_sf_bessel_Y1( $_[0] );
}

sub test {
    return $_[0] + 2;
}

MainLoop;
exit(1);
