// Verify Password
//

// CryptoMemory Library Include Files
#include "CM_LIB.h"
#include "CM_I2C.h"
#include "CM_I2C_L.h"
#include "CM_GPA.h"
#include <stdio.h>

uint8_t ucCmdPassword[4] = {0xba, 0x00, 0x00, 0x03};
uint8_t ucPSW[3];

// Verify Password
uint8_t cm_VerifyPassword(uint8_t * pucPassword, uint8_t ucSet, uint8_t ucRW)
{
	uint8_t i, j;
    uint8_t ucReturn;
	uint8_t ucAddr;
	
	// Build command and PAC address
    ucAddr = CM_PSW + (ucSet<<3);
	ucCmdPassword[1] = ucSet;// to choose which sets of passwords
	if (ucRW != CM_PWWRITE) {
	  	ucCmdPassword[1] |= 0x10;
	  	ucAddr += 4;
	}
	  
	// Deal with encryption if in authenticate mode
	for (j = 0; j<3; j++) {
	    // Encrypt the password
	    if(ucCM_Authenticate) {
    	    for(i = 0; i<5; i++) cm_GPAGen(pucPassword[j]);
    		ucPSW[j] = Gpa_byte;
	  	}
	    // Else just copy it
		else ucPSW[j] = pucPassword[j];
    }
	  
	// Send the command
	ucReturn = cm_WriteCommand(ucCmdPassword, ucPSW, 3);
    // Wait for chip to process password
    CM_LOW_LEVEL.WaitClock(30);	//3
   
    // Read Password attempts counter to determine if the password was accepted
    if (ucReturn == SUCCESS) {
        ucReturn = cm_ReadConfigZone(ucAddr, ucPSW, 1);
	    if (ucPSW[0]!= 0xFF) ucReturn = FAILED;
	}
	if (ucCM_Authenticate && (ucReturn != SUCCESS)) cm_ResetCrypto();
    // Done
    return ucReturn;
}
