Imports System
Imports System.IO
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices

<SqlUserDefinedAggregate(Format.Native, _
 IsInvariantToDuplicates:=False, _
 IsInvariantToNulls:=True, _
 IsInvariantToOrder:=True)> _
<Serializable()> _
<StructLayout(LayoutKind.Sequential)> _
Public Class ComplexSum

    Dim result As ComplexNumber

    Public Sub Init()
        result.realpart = 0
        result.imagpart = 0
    End Sub

    Public Sub Accumulate(ByVal next1 As ComplexNumber)
        If next1.IsNull = True Then
            Return
        End If

        result.realpart += next1.realpart
        result.imagpart += next1.imagpart
    End Sub


    Public Sub Merge(ByVal other As ComplexSum)
        result.realpart += other.result.realpart
        result.imagpart += other.result.imagpart
    End Sub

    Public Function Terminate() As ComplexNumber
        Return result
    End Function
End Class

