#!/usr/bin/env perl
use strict;
use warnings;

use GD::Graph::lines;
use Lingua::EN::Opinion;
use List::Util qw( min max );

my $input_file = shift || die "Usage: perl $0 /some/file.txt\n";
my $term       = shift || 'love';
my $width      = shift || 800;
my $height     = shift || 400;

my $opinion = Lingua::EN::Opinion->new( file => $input_file );
$opinion->analyze(); 

my %scores;
@scores{ @{ $opinion->sentences } } = @{ $opinion->scores };

my $locations = [ map { /$term/ ? $scores{$_} : 0 } @{ $opinion->sentences } ];

my $size = @{ $opinion->scores };

my @data = ( 
    [ 1 .. $size ],     # The x axis labels
    $opinion->scores,   # The sentiment data
    $locations,         # Line showing instances of term
);

my $graph = GD::Graph::lines->new( $width, $height );
$graph->set( 
    x_label       => 'Sentence',
    y_label       => 'Negative/Positive',
    title         => "Usage of $term Over Time",
    transparent   => 0,
    dclrs         => [qw( gray red )],
    line_types    => [ 2, 1 ],
    y_max_value   => max( @{ $opinion->scores } ),
    y_min_value   => min( @{ $opinion->scores } ),
    x_min_value   => 0,
    x_max_value   => $size,
    x_tick_number => $size / 10,
);

my $gd = $graph->plot(\@data);

print $gd->png;
