RGB to Grayscale Conversion

OnFilterStart:
{
  if (imageMode != GrayScaleMode && imageMode != RGBMode)
  {
    ErrorOk("This filter works only with 8-bit images in RGB or Grayscale mode.");
    doAction(CA_CANCEL);
  }
  return false;
}


ForEveryTile:
{

  if (imageMode == RGBMode)
  // Put Grayscale version into channel 0
  // Grayscale conversion similar to Photoshops RGB Mode to Grayscale Mode conversion
  // app. 30% Red, 59% Green, 11% Blue 
  {
    for (y=y_start; y<y_end; y++) 
      for (x=x_start; x<x_end; x++)
        pset( x, y, 0, ( src(x, y, 0) * 76 + src(x, y, 1) * 150 + src(x, y, 2) * 29 ) / 255 );
}

// FILTER CODE that does its weird line art or grayscale thing on channel 0...

if (imageMode == RGBMode) 
// Copy result to channels 1 and 2 
// because a Grayscale image in RGB mode has three identical channels
{
  for (y=y_start; y<y_end; y++) 
    for (x=x_start; x<x_end; x++)
    { 
      pset(x, y, 1, pget(x, y, 0));
      pset(x, y, 2, pget(x, y, 0));
    }
  }

  return true; 
}