/*
 * ARM_CommBlock_v1.c
 *
 *  Created on: Aug 26, 2018
 *      Author: Kasun
 */
#include <string.h>
#include <stdlib.h>
#include "xil_io.h"
#include "ARM_CommBlock_v1.h"
#include "FPGA_CommBlock_v1.h"

char *command;
char *pch;		// local variable
int size = 0;


/******************************************************************************
 * Analyze PC request
 * ****************************************************************************/
xPacaket Analyze_PC_request(char *eth_rx_payload){

#if ARM_COMMBLOCK_DEBUG == 1
	xil_printf("recived = %s\r\n", eth_rx_payload);
#endif
	pch= strtok(eth_rx_payload,",");
	char *word_clave= pch;			// first word is a identifier
#if ARM_COMMBLOCK_DEBUG == 1
	xil_printf("1st word = %s\r\n", word_clave);
#endif
	pch = strtok(NULL, ",");
	size= atoi(pch);			// second field if the size
	// read all the things (for example register numbers)
//	u32 addr[size];
	for(int i=0; i<size; i++){
		pch = strtok(NULL, ",");
		addr[i]=atoi(pch);
	  }

	// read the values corresponding to the previous field
	pch = strtok(NULL, ",");
	command = pch;					// read the command: read_reg, write_reg, etc
#if ARM_COMMBLOCK_DEBUG == 1
	xil_printf("command = %s\r\n", command);
#endif
	for(int i=0; i<size; i++){
		pch = strtok(NULL, ",");
		values[i]=atoi(pch);
	}

	xPacaket rtnPack;
	rtnPack.size = size;
	rtnPack.addr = addr;
	rtnPack.values = values;
	rtnPack.cmd = command;

	return rtnPack;
}


/*****************************************************************************
 * Exacute PC request
 *****************************************************************************/

txPacket Execute_PC_request(xPacaket *rxpack){
	txPacket return_pack;
	static char *command;
	unsigned int *tmpaddr, *tmpvalues;
	int tmpsize;

	command = rxpack->cmd;
	tmpaddr = rxpack->addr;
	tmpvalues = rxpack->values;
	tmpsize = rxpack->size;

#if ARM_COMMBLOCK_DEBUG == 1
	xil_printf("execute cmd = %s\n", command);
#endif

	if(strncmp(command, "read_reg", 8) == 0){

	}
	else if(strncmp(command, "write_reg", 9) == 0){
		Write_registers(tmpaddr, tmpvalues, tmpsize);
		return_pack.len = 0;
		return_pack.txaddr = 0;
	}
	else if(strncmp(command, "read_mem", 8) == 0){

	}
	else if(strncmp(command, "write_mem", 9) == 0){

	}
	else if(strncmp(command, "read_sfifo", 10) == 0){

		unsigned int addrst = Read_FIFO_Stream(tmpaddr, tmpvalues, tmpsize);
#if ARM_COMMBLOCK_DEBUG == 1
		xil_printf("return stream fn = 0x%x\n", addrst);
#endif
		return_pack.len = *tmpvalues;
		return_pack.txaddr = addrst;
	}



	else if(strncmp(command, "write_sfifo", 11) == 0){

	}
	else if(strncmp(command, "stop", 4) == 0){
		xil_printf("receive cmd = stop \n\r");
		strvar = "stop";
//		eTxCnt = 0;
	}
	else if(strncmp(command, "arm_stop", 8) == 0){
		xil_printf("receive cmd = arm_stop \n\r");
//		gloablStr = "arm_stop";
		strvar = "stop";
//		eTxCnt = 0;
	}

	return return_pack;
}


