#!/bin/perl

open IN,"<Ionela1.pnm";
open OUT,">Ionela.sh";
my $header=<IN>;
if($header=~m/^P3/)
{
  print "P3 PNM Format detected. Good. Converting ...\n";
  my $creatorcomment=<IN>;
  my $size=<IN>;
  if($size=~m/^(\d+) (\d+)/)
  {
    my $xsize=$1; my $ysize=$2;
    print "Format: $1x$2\n";
	
	foreach my $y(0 .. ($ysize-1))
	{
	  foreach my $x(0 .. ($xsize-1))
	  {
	    my $r=<IN>; print "r: $r "; $r>>=3; print "r2: $r ";
	    my $g=<IN>; print "g: $g "; $g>>=2; print "g2: $g ";
	    my $b=<IN>; print "b: $b "; $b>>=3; print "b2: $b "; 
		
	    my $p1=($r<<3) | ($g >>5);
		#print "p1: $p1 "; 
        my $p2=(($g&0x07)<<5) | $b;
		my $p=($p1<<8) | $p2;
		#print "p2: $p2  $p: $p\n\n"; 
            my $addr=0x40000+$x*2+$y*240*2;
            print OUT "poke ".sprintf("0x%X",$addr)." $p1\n";
            print OUT "poke ".sprintf("0x%X",$addr+1)." $p2\n";
	  }
	}
	
  }
  
}
