/*
    This file is part of the ChipWhisperer Example Targets
    Copyright (C) 2012-2017 NewAE Technology Inc.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "hal.h"
#include <stdint.h>
#include <stdlib.h>

#include "simpleserial.h"
uint8_t P_Buf[8];
uint8_t K_Buf[8];
uint8_t C_Buf[8];
uint32_t S[2];
uint32_t temp = 0;
uint8_t get_key(uint8_t* k)
{
	// Load key here
	for(uint8_t i=0; i<8; i=i+1) 
	{
	  K_Buf[i]=k[i];
	}
	putch('A');
	for(uint8_t i=0; i<2; i=i+1)
        {
          temp = 0;
          for(uint8_t j=4; j>0; j=j-1)
          {
             temp = temp <<8;
             temp = temp ^ k[(i*4)+j-1];
          }
          S[i]=temp;
	  putch('S');
        }
        //S[0] = k[0];
	putch('S');
	return 0x00;
}

uint8_t get_pt(uint8_t* pt)
{
	/**********************************
	* Start user-specific code here. */
        for(uint8_t i=0; i<8; i=i+1)
	{
          P_Buf[i]=pt[i];
        }
	putch('B');
	trigger_high();
	
	//16 hex bytes held in 'pt' were sent
	//from the computer. Store your response
	//back into 'pt', which will send 16 bytes
	//back to computer. Can ignore of course if
	//not needed
	for(uint8_t i=0; i<8; i=i+1) C_Buf[i]=(P_Buf[i]^K_Buf[i]);
	trigger_low();
	/* End user-specific code here. *
	********************************/
	if(S[0]==0)
	  putch('D');
        simpleserial_put('r', 8, C_Buf);
	return 0x00;
}

uint8_t reset(uint8_t* x)
{
	// Reset key here if needed
	return 0x00;
}

int main(void)
{
    platform_init();
	init_uart();	
	trigger_setup();
	
 	/* Uncomment this to get a HELLO message for debug */
	
	putch('h');
	putch('e');
	putch('l');
	putch('l');
	putch('o');
	putch('\n');
	
		
	simpleserial_init();		
	simpleserial_addcmd('k', 8, get_key);
	simpleserial_addcmd('p', 8, get_pt);
	simpleserial_addcmd('x', 0, reset);
	while(1)
		simpleserial_get();
}
