#!/usr/bin/python

# tz_credit_card.py
#       --copyright--                   Copyright 2009 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       May 6, 2009             bar     quick way to give a bogus card number to a site that doesn't seem to have an unsubscribe
#       November 12, 2011       bar     correct url
#       May 27, 2012            bar     doxygen namespace
#       --eodstamps--
##      \file
#       \namespace              tzpython.tz_credit_card
#
#
#       Check credit card numbers.
#
#


import  re


#
#   From Wikipedia http://en.wikipedia.org/wiki/Luhn_algorithm
#
def check_number(digits):
    """ Check a card number in an array of digit-ints. """

    _sum    = 0
    alt     = False
    digits  = list(digits)
    digits.reverse()

    for d in digits :
        if alt:
            d      *= 2
            if d    > 9:
                d  -= 9
        _sum       += d
        alt         = not alt

    return((_sum % 10) == 0)



def check_ccs(s) :
    """ Check a card number in a string. """

    s   = re.sub(r"[^0-9]", "", s)

    return(check_number([ ord(c) - ord('0') for c in s ]))



def check_ccn(n) :
    """ Check a long integer card number. """

    d   = []
    while n :
        d.append(n % 10)
        n  = n / 10

    d.reverse()

    return(check_number(d))


if  __name__ == '__main__' :
    import  os
    import  sys

    import  TZCommandLineAtFile

    program_name    = os.path.split(sys.argv.pop(0))[1]
    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)


    cn      = None
    r       = False

    while sys.argv :
        cn  = sys.argv.pop(0)

        r   = check_ccs(cn)

        print cn, r


    if (cn != None) and r :
        bca = [ ord(c) - ord('0') for c in re.sub(r"[^0-9]", "", cn) ]
        bca[0]      = 1
        bca[1]      = 1
        bca[2]      = 1
        bca[3]      = 1

        bcn = 0
        m   = 1
        bca.reverse()
        for d in bca :
            bcn    += (d * m)
            m      *= 10

        while True  :
            r       = check_ccn(bcn)
            if  r   :
                print "Valid similar number:", bcn
                break
            bcn    += 1
            pass
        pass

    pass


#
#
#
# eof
