#!/usr/bin/perl

use strict;
use GD;

my $build34file = "build34.map.txt";
my $build33file = "Successful.SNPS.15042005.txt";

my $build34 = ReadBuild( $build34file );
my $build33 = ReadBuild( $build33file );

my $n34 = $#$build34;
my $n33 = $#$build33;

my $width = $n34/10+2;
my $height = $n33/10+2;
my $offset = 30;
my $image = new GD::Image( $offset + $width, $offset + $height );
my $black = $image->colorAllocate( 0,0,0 );
my $red = $image->colorAllocate( 255, 0,0);
my $white = $image->colorAllocate( 255, 255, 255);

$image->filledRectangle( 0, 0, $offset+$width, $offset+$height, $white );
$image->rectangle( $offset, 0, $offset+$width, $height, $black );

my $idx1 = {};
my $idx2 = {};

my $i = 0;  
foreach my $item ( @$build33 ) {
  my ( $marker, $chr, $pos ) = @$item;
  $idx1->{$marker} = $i++;
}

$i = 0;
foreach my $item ( @$build34 ) {
  my ( $marker, $chr, $pos ) = @$item;
  $idx2->{$marker} = $i++;
}

my $lastchr = undef;
$i=0;
foreach my $item ( @$build33 ) {
  my ( $marker, $chr, $pos ) = @$item;
  if ( $lastchr ne $chr ) {
    $image->line( $offset, $i/10, $offset+$width, $i/10 , $black );
  }
  $lastchr = $chr;
  $i++;
}


$lastchr = undef;
$i=0;
foreach my $item ( @$build34 ) {
  my ( $marker, $chr, $pos ) = @$item;
  if ( $lastchr ne $chr ) {
    $image->line( $offset+$i/10, 0, $offset+$i/10, $height-$offset , $black );
  }
  $lastchr = $chr;
  $i++;
}

foreach my $item ( @$build34 ) {
  my ( $marker, $chr, $pos ) = @$item;
  $image->line( $offset + $idx2->{$marker}/10, $idx1->{$marker}/10,$offset + $idx2->{$marker}/10, $idx1->{$marker}/10, $red);
}



open(PNG, ">compare.png");
binmode(PNG);
print  PNG $image->png;
close(PNG);


sub ReadBuild {
  my ($file) = @_;
  open(FILE, $file ) || die "could not open $file\n";
  my @build;
  while(<FILE>) {
    chomp;
    my ( $snp, $chr, $pos ) = split;
    push @build, [$snp, $chr, $pos];
  }

  my @build = sort { my $n = $a->[1] cmp $b->[1]; $n = $a->[2] <=> $b->[2] if ( ! $n ); $n; } @build;
  return \@build;
}
