/**
  * @file Utils.c
  * @brief Utils
  */

/* Includes ------------------------------------------------------------------*/

#include "Utils.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

/** 
  * @defgroup utils Utils
  * @brief Utils
  */

/** @addtogroup utils Utils
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/**
  * @brief Revers strins
  * @param *str: Source string
  * @retval char*: Result string
  */
static char *strrev(char *str)
{
	char *p1, *p2;
	int len;

	if (!str || !*str)
	{
		return str;
	}
	
	len = strlen(str) - 1;
	
	for (p1 = str, p2 = str + len; p2 > p1; ++p1, --p2)
	{
		*p1 ^= *p2;
		*p2 ^= *p1;
		*p1 ^= *p2;
	}

	return str;
}

/**
  * @brief Integer to ASCII
  * @param num: Integer
  * @param *str: String buffer
  * @param base: 10, 16
  * @retval char*: Pointer to buffer
  */
char *itoa(int num, char *str, int base)
{
    int i = 0;
    uint8_t isNegative = 0;
 
    /* Handle 0 explicitely, otherwise empty string is printed for 0 */
    if (num == 0)
    {
        str[i++] = '0';
        str[i] = '\0';
		
        return str;
    }
 
    // In standard itoa(), negative numbers are handled only with 
    // base 10. Otherwise numbers are considered unsigned.
    if (num < 0 && base == 10)
    {
        isNegative = 1;
        num = -num;
    }
 
    // Process individual digits
    while (num != 0)
    {
        int rem = num % base;
        str[i++] = (rem > 9) ? (rem - 10) + 'A' : rem + '0';
        num = num / base;
    }
 
    // If number is negative, append '-'
    if (isNegative)
	{
        str[i++] = '-';
	}
 
    str[i] = '\0'; // Append string terminator
 
    // Reverse the string
    strrev(str);
 
    return str;
}

/**
  *@} 
  */
