Attribute VB_Name = "mdlMisc"
Option Explicit

' http://www.grao.bg/esgraon.html

Public Function ValidateEGN(strEGN As String) As Boolean
  Dim strDay As String
  Dim strMonth As String
  Dim strYear As String
  
  Dim D() As Byte
  Dim intCheckSum As Integer
  Dim intEGNWeights(9) As Integer
  
  Dim intDateC As Integer
  Dim J As Integer, I As Integer
  
  If Len(strEGN) <> 10 Then
    ValidateEGN = False: Exit Function
  
  End If
  
  strDay = Mid$(strEGN, 5, 2)
  If (CInt(strDay) < 1) Or (CInt(strDay) > 31) Then
    ValidateEGN = False: Exit Function
    
  End If
  
  strMonth = Mid$(strEGN, 3, 2)
  If CInt(strMonth) > 40 Then
    intDateC = 40
  
  ElseIf CInt(strMonth) > 20 Then
    intDateC = 20
  
  End If
    
  If (CInt(strMonth) < 1) Or ((CInt(strMonth) - intDateC) > 12) Then
    ValidateEGN = False: Exit Function
  
  End If
  
  intEGNWeights(0) = 2
  intEGNWeights(1) = 4
  intEGNWeights(2) = 8
  intEGNWeights(3) = 5
  intEGNWeights(4) = 10
  intEGNWeights(5) = 9
  intEGNWeights(6) = 7
  intEGNWeights(7) = 3
  intEGNWeights(8) = 6
    
  ' Unicode
  D = strEGN
  
  For J = 0 To UBound(D) - 2 Step 2
    intCheckSum = intCheckSum + (CInt(Chr$(D(J))) * intEGNWeights(I))
    
    I = I + 1
    
  Next J
  
  intCheckSum = intCheckSum Mod 11
  If intCheckSum = 10 Then
    intCheckSum = 0
  
  End If
    
  If intCheckSum = CInt(Right$(strEGN, 1)) Then
    ValidateEGN = True
  
  End If
    
End Function
