#!/usr/bin/perl -w
#################################################################
#                                                               #
#   Pipe demonstration program for receiving from a pipe and    #
#                        sending to a GUI                       #
#                                                               #
#################################################################

# here, instead of a device on serial 1, we are just going to output
# to the GUI screen

use Tk;

sub printit;
$counterval = "nnnnnnnn\ntt-tt-tt";
&makegui;
MainLoop;  # run program loop
exit (0);

sub collect {
#open the pipe for input
open (PIPE, "+</srv/www/cgi-bin/wgiagc/webctr") or die $!;
  while (<PIPE>) {
    chomp;
    $a = $_;
    #get the function - use this to make it multifunctional.
    $a =~ m/^(..) (.+)/;
    $fn = $1;
    $val = $2;
    if ($fn eq "cn") {
      printit "$val";
    } else {
      # you can put what you like in here
      printit "$val";
    }
  };
close PIPE;

exit (0);
}
sub printit {
  $a = shift;
  $t = localtime;
  $lasttime = substr($t, 11, 8);
  # use the next line if you are using a nixie tube counter with 8 digits
#  $cntrvl = substr ("        $a", -8);
  # instead, use these three for the Tk GUI...
  1 while ($a =~ s/(\d+)(\d\d\d)/$1,$2/); # put in all of those commas
  $d = 0; $d = $a =~ m/,/g;               # count the number of commas and add it to the length
  $cntrvl = substr ("        $a", -8 - $d); # 8 digits plus commas

  $counterval = "$lasttime\n$cntrvl";
  $fr -> update;
  # make the console beep if you are using a console
  print "\a";
}

sub makegui {
  $mw = MainWindow  -> new(-title => "Web Counter",
                              -bd => 10,
                              -bg => "#332800",
                                     );
  # bottom buttons
  $mw -> Label (-text => 'Web Counter:     ',
                  -fg => "#ffdb4c",
                  -bg => "#332800",
                                     ) -> pack (-side => 'top');
  $fr = $mw -> Frame (-borderwidth => 0,
                            -width => "15"
                                     ) -> pack (-side => 'top', fill => "x");
  $fr -> Label (-textvariable => \$counterval,
                          -fg => "#ffdb4c",
                          -bg => "#332800"
                                     ) -> pack (-side => 'bottom', fill => "x");
  # make it start the pipe-watching loop after 1,500ms
  $mw -> after (1500, \&collect);
}
