/* VectorNav HSI Calibration Library v1.0.0.2
 *
 * Copyright (c) 2018 VectorNav Technologies, LLC
 *
 * This source code is proprietary to and copyrighted by VectorNav Technologies, LLC and is
 * available solely under license from VectorNav. All rights reserved. If you do not have a
 * license to use this source code from VectorNav, any use hereof is strictly prohibited by
 * U.S. law and other applicable law. This source code is restricted for use solely with the
 * products of VectorNav and as otherwise set forth in any agreement with VectorNav. Any
 * disclosure of this source code to the public or to any third party is also prohibited.
 */
#include "vnstring.h"
#include <string.h>
#if defined(_MSC_VER)
  #pragma warning(push)
  #pragma warning(disable:4255)
#endif
#include <stdio.h>
#if defined(_MSC_VER)
  #pragma warning(pop)
#endif
#include <stdarg.h>
#include "vncompiler.h"

enum VnError
strcpy_x(
    char *dest,
    size_t numOfElements,
    const char *src)
{
  #if VN_HAVE_SECURE_CRT
  if (strcpy_s(dest, numOfElements, src))
    return E_UNKNOWN;
  #else
  if (strlen(src) + 1 > numOfElements)
    return E_BUFFER_TOO_SMALL;

  strcpy(dest, src);
  #endif

  return E_NONE;
}

enum VnError
strcat_x(
    char* dest,
    size_t numOfElements,
    const char *src)
{
  #if VN_HAVE_SECURE_CRT
  if (strcat_s(dest, numOfElements, src))
    return E_UNKNOWN;
  #else
  if (strlen(dest) + strlen(src) + 1 > numOfElements)
    return E_BUFFER_TOO_SMALL;

  strcat(dest, src);
  #endif

  return E_NONE;
}

int
sprintf_x(
    char *buffer,
    size_t sizeOfBuffer,
    const char *format,
    ...)
{
  va_list argptr;
  int result;
  va_start(argptr, format);

  #if VN_HAVE_SECURE_CRT
  result = vsprintf_s(buffer, sizeOfBuffer, format, argptr);
  #else

  /* TODO: Need to add a buffer length check before writing out to the buffer
   *       to avoid overwriting memory. */

  result = vsprintf(buffer, format, argptr);

  if (result > 0 && result + 1 > sizeOfBuffer)
    /* Buffer wasn't big enough. */
    result = -1;

  #endif

  va_end(argptr);

  return result;
}

char*
strtok_x(
    char *str,
    const char *delim,
    char **saveptr)
{
  #if VN_HAVE_SECURE_CRT
  return strtok_s(str, delim, saveptr);
  #elif _SVID_SOURCE || _BSD_SOURCE || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
  return strtok_r(str, delim, saveptr);
  #else
  return strtok(str, delim);
  #endif
}
