;; 
;;=====================================================================================----- 
;; 
;;FUNCTION       LuhnMod() 
;; 
;;ACTION         Generate / Check a string using a form of Luhn's Mod algotithm 
;; 
;;AUTHOR         Glenn Barnas 
;; 
;;VERSION        1.0  - 2010/10/08 
;; 
;;HISTORY        1.0  - 2010/10/08 - Initial Release 
;; 
;;SYNTAX         LuhnMod(string [, flag] [, length]) 
;; 
;;PARAMETERS     String - REQUIRED String 
;;               - the string to check or generate a check value on 
;; 
;;               flag - OPTIONAL - Integer 
;;               - When true, returns the Luhn check value 
;; 
;;               length - OPTIONAL -Integer 
;;               - Specifies an alternate string length. Not reuquired when generating 
;;               a check digit. 
;; 
;;REMARKS        This version defaults to an 11-character string - 10 chars of data 
;;               plus the check digit. If a different length is required, it can  
;;               be specified as an optional parameter. 
;; 
;;RETURNS        Bool for check status (1=Valid), Int containing the check digit 
;;               FLAG=0 - 1 (true) if a valid check, 0 (false) otherwise 
;;               FLAG=1 - Digit needed for the supplied string to pass the check 
;; 
;;DEPENDENCIES   sLM() - included secondary function 
;; 
;;TESTED WITH    W2K, WXP, W2K3, W2K8, Win7 
;; 
;;EXAMPLES       $S = '02C 
; 
Function LuhnMod($_Check, OPTIONAL $_Flag, OPTIONAL $_Len)
 
  Dim $_F					; cycle flag 
  Dim $_S					; Subtotal 
  Dim $_Cv					; Check value 
 
  $_F = 1
 
  $_Check = UCase($_Check)			; force all upper-case 
  If Val($_Len) = 0 $_Len = 11 EndIf
 
  If Len($_Check) <> $_Len And Not $_Flag	; verify length 
    $LuhnMod = 0
    Exit 87
  Else
    If Not $_Flag				; strip the check digit 
      $_S = Val(Right($_Check, 1))
      $_Check = Left($_Check, Len($_Check) - 1)
    EndIf
  EndIf
 
  While $_Check
    $_F = $_F ^ 1				; get last char 
 
    $_Cv = Asc(Right($_Check, 1)) - 48		; as ASCII, then reduce 
 
    If $_Cv > 9
      $_Cv = sLM($_Cv)				; perform luhn check 
    EndIf
 
    If $_F
      $_Cv = sLM($_Cv * 2)
    EndIf
    $_S = $_S + $_Cv
 
    $_Check = Left($_Check, ~)
  Loop
 
 
 
  If $_Flag
    $LuhnMod = 0
    If $_S Mod 10 
      $LuhnMod = 10 - ($_S Mod 10)		; return check digit 
    EndIf
  Else
    $LuhnMod = Not ($_S Mod 10)			; return status 
  EndIf
 
  Exit 0
 
EndFunction
 
; Secondary function 
Function sLM($_Val)
 
  Dim $_Lv, $_Rv			; values 
 
  $sLM = $_Val
 
  If $_Val < 10
    Exit 0
  EndIf
 
  $_Lv = Val(Left($_Val, 1))
  $_Rv = Val(Right($_Val, 1))
 
  $sLM = sLM($_Lv + $_Rv)
 
  Exit 0
 
EndFunction