def process_card(connection, options):
    global log_level

    # Which CLA to probe?
    PROBE_CLA = 0xFF

    # Open card
    card = CAC(connection)

    print "Trying some interesting APDUs"
    
    for i in range(0xff+1):
        for j in range(0xff+1):
            apdu_data = APDU.READ_BINARY(i, j, CLA=PROBE_CLA)
            data, sw1, sw2  = card._send_apdu(apdu_data)
            if sw1 == 0x90:
                print "Success at %x %x"%(i,j)
                print data
    
#     apdu_data = APDU.GET_DATA(0x00, 0x01, CLA=0xFF)
#     card._send_apdu(apdu_data)
if __name__ == "__main__":

    # Import our command line parser
    from llsmartcard import parser
    opts = optparse.OptionParser()

    # parse user arguments
    parser.command_line(opts, process_card)
    #        (data, sw1, sw2) = card.apdu_reset_retry_counter(PIN_DATA, 0x80, PIN_DATA)

    print("Opening Secure Channel")

    # Select GP Manager
    card.apdu_select_application(APDU.APPLET.SECURITY_GEMALTO)
    # Open our secure channel
    card.open_secure_channel(APDU.APPLET.SECURITY_GEMALTO,
                             APDU.AUTH_KEYS.GEMALTO,
                             security_level=APDU.SECURE_CHANNEL.MODE.NONE)

    # Reset our retry counter
    print("Resetting retry counter...")
    #    card.apdu_change_reference_data(0x00, [], PIN_DATA, first=True)
    card.apdu_change_reference_data(0x80, PIN_DATA, PIN_DATA)
    card.apdu_reset_retry_counter(PIN_DATA, 0x80, PIN_DATA)

    # Print applications on the card
    print("Printing card applications...")
    card.print_applications()


if __name__ == "__main__":

    # Import our command line parser
    from llsmartcard import parser
    opts = optparse.OptionParser()

    # parse user arguments
    parser.command_line(opts, process_card)
        print("Printing NIST PIV Objects... (PIN PROTECTED)")
        data = card.read_object(APDU.APPLET.NIST_PIV,
                          APDU.OBJ_NIST_PIV.FACE,
                          pin=PIN)
        picture = data[0][1]
        with open("user_face.jp2", "w") as f:
            import re
            container_string = "".join([chr(int(x)) for x in re.findall(r"\d+", str(picture))])
            #import pdb; pdb.set_trace()
            found = container_string.find("\xFF\x4F\xFF\x51")
            if(not found): raise Exception("No JPEG 2000 photo!")
            f.write(container_string[found:])
        image = Image.open("user_face.jp2")
        image.save("user_cac_image.jpeg", "JPEG")
        #import pdb; pdb.set_trace()
        print("Printing DoD CAC Objects... (PIN PROTECTED)")
        card.print_object(APDU.APPLET.DOD_CAC,
                          APDU.OBJ_DOD_CAC.CAC_PERSON,
                          pin=PIN)



if __name__ == "__main__":

    # Import our command line parser
    from llsmartcard import parser
    opts = optparse.OptionParser()

    # parse user arguments
    parser.command_line(opts, dump_photo)