Hello!

I am unable to fix the following problem on my own so far despite like 10 hours of trying it:

There is a very good example of an edge detection algorithm by Olaf Schmidt here:

I was searching for a grayscale function, and I wanted to use the one shown in this project.
The grayscale function in this project discards the alpha channel while I must preserve it in my project.

I tried change to the function to preserve the alpha channel, but I am experiencing an overflow problem.
I am not sure if the math formula is actually correct and it's only a VB6 problem, or if my approach is generally faulty.

I have not been able to fix the overflow problem in the following attempt.
Can somebody help me resolve it?

Thank you!

Code:
Public Function Grayscale(SrcSrf As cCairoSurface) As cCairoSurface
Dim x As Long, y As Long, xL As Long, Src() As Byte, Dst() As Byte, DstL() As Long
  
  Static SqrLut(0 To 255, 0 To 255) As Long, LogLut(2 To 130052) As Byte, LLut&(0 To 255)
  If LogLut(130052) = 0 Then 'init the lookup-tables (for squared deltas, logarithmic scaling and 32Bit-GreyValues)
    For y = 0 To 255: For x = 0 To 255: SqrLut(x, y) = (x - y) ^ 2 + 1: Next x, y
    For x = 2 To 130052: LogLut(x) = Log(x) * 23 - 16: Next 'in a normal Roberts, we would use Sqr() instead of Log()
    For x = 0 To 255: LLut(x) = (x + 256 * x + 65536 * x) Or &HFF000000: Next
  End If

  SrcSrf.BindToArray Src
  Set Grayscale = Cairo.CreateSurface(SrcSrf.Width, SrcSrf.Height)
      Grayscale.BindToArray Dst
      Grayscale.BindToArrayLong DstL

        For y = 1 To UBound(Src, 2)
            xL = 1
            For x = 4 To UBound(Src, 1) Step 4
                'Calculate the gray value
                Dim grayValue As Long
                grayValue = LogLut(SqrLut(Src(x, y), Src(x - 4, y - 1)) + _
                SqrLut(Src(x - 4, y), Src(x, y - 1)))
                
                'Put the gray values into the rgb channels
                DstL(xL, y) = (grayValue + 256 * grayValue + 65536 * grayValue) ' grayscale for R, G, B
                
                ' Preserve the alpha value of the source array
                DstL(xL, y) = CDbl(DstL(xL, y)) Or CDbl((Src(x + 3, y))) * CDbl(&H1000000)   ' Alpha value of original source
                
                xL = xL + 1
            Next x
        Next y

 
  SrcSrf.ReleaseArray Src
  Grayscale.ReleaseArray Dst
  Grayscale.ReleaseArrayLong DstL

End Function