#include "test_common.h"

CK_SLOT_ID_PTR SlotList = NULL;
CK_ULONG SlotCount = 0;
int
main(int argc, char *argv[]){
	CK_RV rc;
	CK_SLOT_INFO sinfo;
	CK_ULONG i, j;
	CK_SLOT_ID SlotId;

	printf("Info test\n");
	for (i=1; i<(CK_ULONG)argc; i++) {
		if (strcmp("-api", argv[i]) == 0) {
			++i;
			api_path = argv[i];
		}
	}
	// Load the PKCS11 library
	rc = init(api_path, &funcs, NULL);
	if (rc != CKR_OK) {
		printf("init failed\n");
		return rc;
	}

//	for (i=0; i<10; i++) { 
		rc = funcs->C_GetSlotList(CK_FALSE, NULL, &SlotCount);
		if (rc != CKR_OK) {
			SlotList = NULL;
			printf("Get slot list result: 0x%x\n", rc);
			return rc;
		}
		printf("%d slots found\n", SlotCount);
		if (SlotCount > 0)
		{   
			SlotList = (CK_SLOT_ID_PTR) malloc(SlotCount * sizeof(CK_SLOT_ID));
			rc = funcs->C_GetSlotList(CK_FALSE, SlotList, &SlotCount);
			if (rc != CKR_OK) {
				SlotList = NULL;
				SlotCount = 0;
				printf("Get slot list result: 0x%x\n", rc);
				return rc;
			}
		} else {
			SlotList = NULL;
			return CKR_OK;
		}

		printf("Cycle through slot list\n");
		for (j = 0; j<SlotCount; j++) 
		{
			SlotId = SlotList[j];
			// Display the current token and slot info 
			rc = display_slot_info(funcs, SlotId);
			if (rc != CKR_OK) {
				printf("display slot info failed\n");
				return rc;
			}
			rc = funcs->C_GetSlotInfo(SlotId, &sinfo);
			if (sinfo.flags & CKF_TOKEN_PRESENT) {
				rc = display_token_info(funcs, SlotId);
				if (rc != CKR_OK) {
					if (rc == CKR_TOKEN_NOT_RECOGNIZED) {
						printf("Token not recognized\n");
					} else {
						printf("display_token_info failed\n");
					}
//					return rc;
				}
			}
		}

		if(SlotList){free(SlotList);SlotList=NULL;}
/*
		printf("Press Ctrl-C for exit, ENTER to continue\n");
#ifndef WIN32    
		echo(FALSE);
		c = getc(stdin);
		echo(TRUE);
#else      
		c = _getch();
#endif	  
		if (c == 0x03) 
		{
			// Input terminated (Ctrl-C)
			break;
		}
*/
//	}
	printf("Info test SUCCESS\n");
	return CKR_OK;
}
