#!/usr/bin/perl -w
#
# topscan.pl: perl utility to analyze X-ray diffraction topographs 
#
# Richard Jones, University of Connecticut
# November 1, 2006
#

use GD;
use GD::Text;
use GD::Graph::linespoints;
use X11::GUITest qw/GetMousePos/;
use Image::Magick;

my ($border,$topmargin);
my ($imagewidth,$imageheight,$imagehoffset,$imagevoffset);

$border = 5;
$topmargin = 50;
$imagewidth = 210;
$imageheight = 210;
#$imagehoffset = 410;
#$imagevoffset = 480;
#$imagewidth = 1024;
#$imageheight = 1024;
$imagehoffset = 700;
$imagevoffset = 400;
$geometry = sprintf("%dx%d+%d+%d",$imagewidth,$imageheight,
                                  $imagehoffset,$imagevoffset);

GD::Text->font_path('/usr/X11R6/lib/X11/fonts/TTF');

my $gdplot = GD::Graph::linespoints->new(800, 500);
   $gdplot->set_title_font('Vera',18);
   $gdplot->set_x_label_font('Vera',14);
   $gdplot->set_y_label_font('Vera',14);
   $gdplot->set_x_axis_font('Vera',12);
   $gdplot->set_y_axis_font('Vera',12);
$gdplot->set( 
      x_label       => 'rocking curve step',
      y_label       => 'pixel intensity',
      x_label_skip  => int(($#ARGV+1)/10),
      title         => 'Pixel Rocking Curve',
      dclrs         => [ qw(blue green pink blue cyan) ], 
      line_types    => [1, 2, 3, 4],
      fgclr         => 'black',
      labelclr      => 'black',
      axislabelclr  => 'black',
      legendclr     => 'black',
      valuesclr     => 'black',
      textclr       => 'black',
      marker_size   => 2,
      transparent   => 0
  ) or die;

$image=Image::Magick->new;
$rimage=Image::Magick->new;
$graph=Image::Magick->new;

foreach $file (@ARGV) {
   $image->Read($file);
}

$image->Crop(geometry=>$geometry);
$image->Set(delay=>10);
$image->Magnify();
while (1>0) {
   $image->Animate();
   ($x,$y) = GetMousePos();
   $x = int(($x-$border));
   $y = int(($y-$topmargin-$border));
   my (@xlist,@ylist);
   for ($i=0;$image->[$i];$i++) {
      my ($r,$g,$b);
      ($r,$g,$b) =  $image->[$i]->GetPixels(width=>1,height=>1,x=>$x,y=>$y);
      $xlist[$i] = $i;
      $ylist[$i] = $r;
   }
   my @data = (\@xlist,\@ylist);
   my $gd = $gdplot->plot(\@data) or die;
   open(IMG,">curve.jpeg") or die $!;
   binmode IMG;
   print IMG $gd->jpeg;
   close IMG;
   $graph->Read("curve.jpeg");
   $graph->Display();
}
