### The Blue Dither algorithm itself (acting on RGBA values of the pixels)

use 'GFX-Tools-Buffer::matrix'; ### uses this math matrix class !

sub new {
    my $class = shift;

    $self = { colorkeyRed => -1, colorkeyGreen => -1, colokeyBlue => -1, }; ### amount of dither 

    bless $self, $class;
}

sub setColorkeyRGBA {
  my ($self, $R, $G, $B) = @_;

  ($R >= 0 and $B >= 0 and $B >= 0 and $R < 256 and $G < 256 and $B < 256) or
    die "MatrixBitmapSelector : R,G or B colors are ont between 0 and 255.\n"
  
  $self->{colorkeyRed} = $R;
  $self->{colorkeyGreen} = $G;
  $self->{colorkeyBlue} = $B;
}

sub selectColorAndSave {
  my ($self, $matrixbitmapobj) = @_;

  my $matrix = $matrixbitmapobj->getMatrix;

  ### set full random matrix to negative color numbers
  for (my $j = 0; $j < $matrix->getRowsNumber * $pngbppmultiplynumber; $j++) {
    for (my $i = 0; $i < $matrix->getColumnsNumber; $i++) {
      $matrix->setAtIndex($j, $i, -1);
    }
  }


  
  my $matrixwithselection = matrix->new($matrix->getRowsNumber, $matrix->getColumnsNumber);
  
  my $pngbppmultiplynumber = 4 - 1; ### R,G,B and A
    
  for (my $j = 0; $j < $matrix->getRowsNumber * $pngbppmultiplynumber; $j++) {
    for (my $i = 0; $i < $matrix->getColumnsNumber; $i++) {
      ### rgbanumber is red, green, blue or alpha byte in the matrix

      my $selectionflag = 0;
      ### NOTE : this 'for' goes down
      for (my $rgbanumber = $pngbppmultiplynumber; $rgbanumber >= 0; $rgbanumber--) {
	### 
	if ($rgbanumber == 3 and $self->{colorkeyRed} == $matrix->indexOf($j, $i)) {
	  $selectionflag++;
	} else if ($rgbanumber == 2 and $self->{colorkeyGreen} == $matrix->indexOf($j, $i)) {
	  $selectionflag++;
	} else if ($rgbanumber == 1 and $self->{colorkeyBlue} == $matrix->indexOf($j, $i)) {
	  $selectionflag++;
	}
	### does not check alpha channel hex
      }
	if ($selectionflag == 3) {
	  $matrixwithselection->setAtIndex($j, $i, $matrix->indexOf($j,$i));
	  $matrixwithselection->setAtIndex($j-1, $i-1, $matrix->indexOf($j-1,$i-1));
	  $matrixwithselection->setAtIndex($j-2, $i-2, $matrix->indexOf($j-2,$i-2));
      }
    }
  }
  ### NOTE : returns a class, a second matrix with only the color to
  ### be selected in
  return MatrixBitmap->new->setMatrix($matrixwithselection);
}

1;
