#include "common.h"
#include "../common/ISO7816-common.h"
#include <stdio.h>
#include <util/delay.h>
#define printf(...) 

#define CARD_PRESENCE_REG_PORT PORTB
#define CARD_PRESENCE_REG_PIN  PINB
#define CARD_PRESENCE_REG_DDR  DDRB
#define CARD_PRESENCE_PIN  2
#define CARD_PRESENCE_INTERUPT INT2
#define CARD_PRESENCE_INTERUPT_EDGE ISC20 //any edge

#define CARD_RESET_REG_PORT PORTD
#define CARD_RESET_REG_DDR  DDRD
#define CARD_RESET_PIN  6

#define CARD_POWER_REG_PORT PORTD
#define CARD_POWER_REG_DDR  DDRD
#define CARD_POWER_PIN  5

#ifndef MIN
	#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif

#define ATR_IS_ERROR(x) (((x) & 0x80) == 0x80)
#define ATR_READ_SUCCESS                 0x00
#define ERR_ATR_TIMEOUT                  0x81
#define ERR_TOO_MANY_ATR_INTERFACE_BYTES 0x82
#define ERR_ATR_CHECKSUM_FAIL            0x83
#define ERR_PROTOCOL_NOT_SUPPORTED       0x84
#define ERR_ATR_CARD_REMOVED             0x85

#ifdef CARD_PRESENCE_INTERUPT
	#include <avr/interrupt.h>
	extern void ISO7816_card_presence_changed(uint8_t inserted);
#endif

#define ISO7816_IS_ERROR(ret) (((ret) & 0xFF) == 0xFF)
#define ISO7816_ERR_TIMEOUT       0xFFFF
#define ISO7816_ERR_CHECKSUM_FAIL 0xFFFE
#define ISO7816_ERR_CARD_REMOVED  0xFFFD
	
void ISO7816_init(void);

uint8_t ISO7816_is_card_present(void);
uint8_t ISO7816_card_power(uint8_t on);
void ISO7816_dumpATR(ISO7816_ATR* atr);
uint8_t ISO7816_readATR(ISO7816_ATR* atr);
uint8_t ISO7816_set_protol(ISO7816_ATR* atr);
uint16_t ISO7816_send_apdu(ISO7816_APDU_Header* apdu_header,
						   uint8_t*  apdu_payload,
						   uint8_t   apdu_payload_length,
						   uint16_t* answer_status,
						   uint8_t*  answer_payload,
						   uint8_t   answer_payload_length);