#!/usr/bin/perl
use Tk ;

my $x_width = 640 ;
my $y_width = 550 ;

my $mywin ;
my $canvas ;

main ( ) ;
$canvas -> delete ( 'all' ) ;

$file = shift ( @ARGV ) ;
$x_max = shift ( @ARGV ) ;
$skip = shift ( @ARGV ) ;
$roll = shift ( @ARGV ) ;

unless ( $x_max )
{
  $x_max = 128 ;
}

open ( INDAT , '<' . $file ) ;

foreach ( 0..$skip )
{
  my $zeile = <INDAT> ;
}

my $y = 0 ;
my $x = 0 ;
my @dataR = ( ) ;
my @dataG = ( ) ;
my @dataB = ( ) ;
my $state = 'R' ;
my @data = ( ) ;

if ( $roll )
{
  my $zeile = <INDAT> ;
  @data = split ( m!\s+! , $zeile ) ;
  @data = splice ( @data , 0 , $roll ) ;
}

while ( !eof(INDAT) )
{
  unless ( @data )
  {
    my $zeile = <INDAT> ;
    @data = split ( m!\s+! , $zeile ) ;
  }

  if ( @data && ( $state eq 'R' ) )
  {
    my $len = $x_max - @dataR ;

    if ( @data < $len )
    {
      push ( @dataR , @data ) ;
      @data = ( ) ;
    }
    else
    {
      my @part = splice ( @data , 0 , $len ) ;
      push ( @dataR , @part ) ;
      $state = 'G' ;
    }
  }

  if ( @data && ( $state eq 'G' ) )
  {
    my $len = $x_max - @dataG ;

    if ( @data < $len )
    {
      push ( @dataG , @data ) ;
      @data = ( ) ;
    }
    else
    {
      my @part = splice ( @data , 0 , $len ) ;
      push ( @dataG , @part ) ;
      $state = 'B' ;
    }
  }

  if ( @data && ( $state eq 'B' ) )
  {
    my $len = $x_max - @dataB ;

    if ( @data < $len )
    {
      push ( @dataB , @data ) ;
      @data = ( ) ;
    }
    else
    {
      my @part = splice ( @data , 0 , $len ) ;
      push ( @dataB , @part ) ;
      $state = 'DISP' ;
    }
  }

  if ( $state eq 'DISP' )
  {
    for ( $x = 0 ; $x < @dataR ; $x ++ )
    {
#      my $fG = sprintf('%02x',hex($dataG[$x])*5) ;
#      my $fB = sprintf('%02x',hex($dataB[$x])*5) ;
#      my $fR = sprintf('%02x',hex($dataR[$x])*5) ;
#      my $farbe = '#' . $fG . $fB . $fR ;

#      my $farbe = '#' . $dataG[$x] . $dataB[$x] . $dataR[$x] ;
      my $farbe = '#' . $dataR[$x] . $dataG[$x] . $dataB[$x] ;

      if ( length($farbe) == 7 )
      {
        $canvas -> create ( 'line' , $x+4 , $y , $x+5 , $y , -fill => $farbe ) ;
      }
    }

    $y ++ ;
    $canvas -> update ( ) ;
    @dataR = ( ) ;
    @dataG = ( ) ;
    @dataB = ( ) ;
    $state = 'R' ;
  }
}

$canvas -> update ( ) ;
close ( INDAT ) ;

$mywin -> MainLoop ;

sub main
{
  if ( Exists ( $mywin ) )
  {
    $mywin -> withdraw ( ) ;
  }

  $mywin = MainWindow -> new ;
  $mywin -> title ( '2D-Grafik' ) ;

  $canvas = $mywin -> Canvas (
  -width => $x_width ,
  -height => $y_width ,
  -relief => 'sunken' ,
  -background => '#ccccee' ,
  -bd => 0
  ) -> pack ( -side => 'top' , -fill => 'both' ) ;
}
