#!/usr/bin/perl

=for Explanation
  This is a fairly simple example of using Demeter to process and plot
  the 60K iron foil data.  This demonstration shows how to obtain the
  basic plotting features of Athena using Demeter.  There is some
  simple keyboard interactivity.  Along with the plot, the code used
  to generate the plot is written to the screen.
  .
  Use the -l command line switch to choose ANSII colors approporiate
  for a screen with a bright background.

=cut

=for Copyright
 .
 Copyright (c) 2006-2019 Bruce Ravel (http://bruceravel.github.io/home).
 All rights reserved.
 .
 This file is free software; you can redistribute it and/or
 modify it under the same terms as Perl itself. See The Perl
 Artistic License.
 .
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

=cut

use Demeter qw(:data);
my $demeter = Demeter->new;
$demeter->set_mode(backend=>1, screen=>0, repscreen=>0, plotscreen=>0);

use Getopt::Long;
my ($light_background, $dark_background, $use_pgplot, $use_gnuplot, $is_dos_shell, $echo) =
  (0, 1, 0, 1, 0, 0);
my $result = GetOptions (
			 "d" => \$dark_background,
			 "l" => \$light_background,
			 "p" => \$use_pgplot,
			 "g" => \$use_gnuplot,
			 "w" => \$is_dos_shell,
			 's' => \$echo,
			);
($light_background = 1) if (not $dark_background);
($use_gnuplot = 1) if (not $use_pgplot);
$demeter->plot_with('gnuplot') if $use_gnuplot;
$demeter->set_mode(screen=>1) if $echo;

use Term::ReadLine;

## ---------------------------------------------------------------
## color with Term::ANSIColor if available, otherwise normal text
use subs qw(BOLD RED RESET YELLOW GREEN BLUE UNDERLINE);
my $ANSIColor_exists = ((not $is_dos_shell) and (eval "require Term::ANSIColor"));
if ($ANSIColor_exists) {
  import Term::ANSIColor qw(:constants);
} else {
  foreach my $s (qw(BOLD RED RESET YELLOW GREEN BLUE UNDERLINE)) {
    eval "sub $s {q{}}";
  };
};
my $INDIC = ($light_background) ? BLUE : YELLOW;


my $term = new Term::ReadLine 'Demeter plotting tests';
my $plot = $demeter->po;

my $dobject = Demeter::Data -> new(group => 'data0');
$dobject -> set(file        => "data/fe.dat",
		fft_kmax    => 3,    fft_kmin  => 14,
		bkg_spl2    => 18,
		bkg_nor2    => 1800,
		energy      => '$1',
		numerator   => '$2',
		denominator => '$3',
		ln          => 1,
		datatype    => 'xmu',
	       );

&query;
my $prompt = "Choose a test by number, h for help, or q to quit > ";
while ( defined ($_ = $term->readline($prompt)) ) {
  exit if ($_ =~ m{\Aq});
  next if ($_ !~ m{\A([1-9ab])});
  plot($_,$dobject);
  &query;
  $plot->start_plot; # reset the plot for the next go around
};

sub query {
  print $/, $/,
    BOLD, RED, "This example shows several basic plots of these iron foil data\n\n", RESET,

    BOLD, $INDIC, " 1.", RESET, " mu + background + pre-edge + post-edge\n",
    BOLD, $INDIC, " 2.", RESET, " normalized mu + normalized background\n",
    BOLD, $INDIC, " 3.", RESET, " flattened mu + flattened background\n",
    BOLD, $INDIC, " 4.", RESET, " derivative of mu\n",
    BOLD, $INDIC, " 5.", RESET, " mu + I0 + signal\n",
    BOLD, $INDIC, " 6.", RESET, " three k-wights, stacked\n",
    BOLD, $INDIC, " 7.", RESET, " |chi(R)| + window\n",
    BOLD, $INDIC, " 8.", RESET, " envelope, real, imaginary in R\n",
    BOLD, $INDIC, " 9.", RESET, " kq plot: chi(k)*k^2 + Re[chi(q)] + window\n",
    BOLD, $INDIC, " a.", RESET, " chi(E)\n",
    BOLD, $INDIC, " b.", RESET, " norm(E)+deriv(E)\n\n",
    BOLD, $INDIC, " q.", RESET, " quit\n\n";
  return 0;
}

sub plot {
  my ($n, $data) = @_;
  print "\n" x 2, GREEN, "## ", "=" x 70, "\n", "## ", RESET;
  eval "plot$n(\$data)";
  print $@, $/;
  spew($n);
  print "\n", UNDERLINE, "Return to continue >", RESET, " ";
  my $how = <STDIN>;
};

sub state {
  my ($t) = @_;
  print GREEN, $t, BOLD, RED;
  chomp($t);
  $demeter->po->title($t);
};

sub spew {
  my ($n) = @_;
  open F, $0 or die "could not open $0 for reading\n";
  my $flag = 0;
  print RESET, $/;
  while (<F>) {
    my $line = $_;
    last if (($line =~ m{sub\s+plot}) and $flag);
    $flag = 1 if (($line =~ m{sub\s+plot([1-9ab])}) and ($1 eq $n));
    print $line if ($flag and ($line !~ m{\A\s*state}));
  };
  close F;
};


sub plot1 {
  my ($data) = @_;
  state("mu + background + pre-edge + post-edge\n");
  $data->po->set(e_mu      => 1,    e_bkg     => 1,
		 e_norm    => 0,    e_der     => 0,
		 e_pre     => 1,    e_post    => 1,
		 e_i0      => 0,    e_signal  => 0,
		 e_markers => 1,
		 emin      => -200, emax      => 2000,
		 space     => 'E',
		);
  $data->plot;
};

sub plot2 {
  my ($data) = @_;
  state("normalized mu + normalized background\n");
  $data->po->set(e_mu      => 1,    e_bkg     => 1,
		 e_norm    => 1,    e_der     => 0,
		 e_pre     => 0,    e_post    => 0,
		 e_i0      => 0,    e_signal  => 0,
		 e_markers => 1,
		 emin      => -200, emax      => 2000,
		 space     => 'E',
		);
  $data->bkg_flatten(0);
  $data->plot;
};

sub plot3 {
  my ($data) = @_;
  state("flattened mu + flattened background\n");
  $data->po->set(e_mu      => 1,    e_bkg     => 1,
		 e_norm    => 1,    e_der     => 0,
		 e_pre     => 0,    e_post    => 0,
		 e_i0      => 0,    e_signal  => 0,
		 e_markers => 1,
		 emin      => -200, emax      => 2000,
		 space     => 'E',
		);
  $data->bkg_flatten(1);
  $data->plot;
};

sub plot4 {
  my ($data) = @_;
  state("derivative of mu\n");
  $data->po->set(e_mu      => 1,    e_bkg     => 0,
		 e_norm    => 0,    e_der     => 1,
		 e_pre     => 0,    e_post    => 0,
		 e_i0      => 0,    e_signal  => 0,
		 e_markers => 1,
		 emin      => -20,  emax      => 120,
		 space     => 'E',
		 );
  $data->set(name=>'derivative')->plot;
  $data->po->e_norm(1);
  $data->set(name=>'norm. deriv.')->plot;
};

sub plot5 {
  my ($data) = @_;
  state("mu + I0 + signal\n");
  $data->po->set(e_mu      => 1,    e_bkg     => 0,
		 e_norm    => 0,    e_der     => 0,
		 e_pre     => 0,    e_post    => 0,
		 e_i0      => 1,    e_signal  => 1,
		 e_markers => 0,
		 emin      => -20,  emax      => 120,
		 space     => 'E',
		 );
  $data->plot;
};

sub plot6 {
  my ($data) = @_;
  state("scale three k-weights to plot together\n");

  $data->po->legend(dy=>0.05, x=>0.73);

  $data->po->set(kweight => 1, kmax => 17, space => 'k');
  $data->set(plot_multiplier => 5,   'y_offset'=>14, name=>'kw=1, scaled by 5');
  $data->plot;

  $data->po->kweight(2);
  $data->set(plot_multiplier => 1,   'y_offset'=>7,  name=>'kw=2, unscaled');
  $data->plot;

  $data->po->kweight(3);
  $data->set(plot_multiplier => 0.2, 'y_offset'=>0,  name=>'kw=3, scaled by 0.2');
  $data->plot;

  $data->set(name=>'My iron data', plot_multiplier=>1); # reset the label
};

sub plot7 {
  my ($data) = @_;
  state("|chi(R)| + window\n");
  $data -> po -> set(kweight => 2, r_pl => 'm', space => 'r', );
  $data -> plot -> plot_window;
};

sub plot8 {
  my ($data) = @_;
  state("envelope, real, imaginary in R\n");
  $data->po->legend(dy=>0.05, x=>0.73);

  $data->po->set(kweight => 2, r_pl => 'e', space => 'r');
  $data->plot;

  $data->set(name=>'Real part');
  $data->po->set(r_pl => 'r', );
  $data->plot;

  $data->set(name=>'Imaginary part');
  $data->po->set(r_pl => 'i', );
  $data->plot;

  $data->set(name=>'My iron data'); # reset the label
};

sub plot9 {
  my ($data) = @_;
  state("kq plot: chi(k)*k^2 + Re[chi(q)] + window\n");
  $data -> po -> set(kweight => 2, 'q_pl' => 'r', qmax => 17);
  $data -> plot('kq') -> plot_window;
};

sub plota {
  my ($data) = @_;
  state("chi(E)\n");
  $data -> po -> set(kweight => 2, space => 'k', chie => 1, emax => 1000);
  $data -> plot;
  $data -> po -> set(chie => 0);
};

sub plotb {
  my ($data) = @_;
  state("norm(E)+deriv(E)\n");
  $data -> plot('ed');
};
