#ifndef __SECURE_CRT_FUNCS_H__
#define __SECURE_CRT_FUNCS_H__

#ifndef SW_NO_SUPPORT_FOR_SECURE_API

#include <altcecrt.h>

#else

// Platform Builder 5.0 has no support for secure APIs.
// -DSW_NO_SUPPORT_FOR_SECURE_API must have been set in the 
// project "sources" file.
// We provide our own versions which are simple wrappers
// to the unsafe APIs.

typedef int errno_t;

inline errno_t __cdecl _tcscpy_s(
    TCHAR *dst,
    size_t sizeInTCHARs,
    const TCHAR *src
)
{
	_tcscpy(dst, src);
	return 0;
}

inline errno_t __cdecl _tcsncpy_s(
    TCHAR *dst,
    size_t sizeInTCHARs,
    const TCHAR *src,
    size_t count
)
{
	_tcsncpy(dst, src, count);
	return 0;
}

inline errno_t __cdecl wcsncpy_s(
    WCHAR *dst,
    size_t sizeInWCHARs,
    const WCHAR *src,
    size_t count
)
{
	wcsncpy(dst, src, count);
	return 0;
}

inline errno_t __cdecl strncpy_s(
    char *dst,
    size_t sizeInChars,
    const char *src,
    size_t count
)
{
	strncpy(dst, src, count);
	return 0;
}

inline errno_t __cdecl _tcscat_s(
    TCHAR *dst,
    size_t sizeInTCHARs,
    const TCHAR *src
)
{
	_tcscat(dst, src);
	return 0;
}

inline errno_t __cdecl memcpy_s(
    void * dst,
    size_t sizeInBytes,
    const void * src,
    size_t count
)
{
	memcpy(dst, src, count);
	return 0;
}

inline TCHAR* __cdecl _itot_s(   
	int value,
	TCHAR *buffer,
	size_t sizeInTCHARs,
	int radix 
)
{
	return _itot(value, buffer, radix);
}

#endif //SW_NO_SUPPORT_FOR_SECURE_API

#ifndef _tcstok_s
inline TCHAR* _tcstok_s(TCHAR* _Str, 
						const TCHAR* _Delim, 
						TCHAR** _Context)
{
	return _tcstok(_Str, _Delim);
}
#endif

#ifndef _stprintf_s
inline int _stprintf_s(TCHAR *buffer,
					   size_t sizeOfBuffer,
					   const TCHAR *format, ... ) 
{
	int nReturn = -1;
	va_list arglist;
	va_start(arglist, format);
	nReturn = _vsntprintf(buffer, sizeOfBuffer, format, arglist);
	va_end(arglist);
	return nReturn;
}
#endif

// _beginthreadex and _endthreadex are not supported on Windows CE 2.1 or later (the C runtime issues with leaking 
// resources have apparently been resolved and they seem to have just ripped out support for the API) so map it to 
// CreateThread on Windows CE.

#define	_beginthreadex( SECURITY_PTR, STACK_SIZE, START_ADDRESS, ARG_LIST, FLAGS, THREAD_ID_PTR )		\
	CreateThread( SECURITY_PTR, STACK_SIZE, (LPTHREAD_START_ROUTINE) START_ADDRESS, ARG_LIST, FLAGS, 	\
				  (LPDWORD) THREAD_ID_PTR )

#define	_endthreadex( RESULT )


#endif //__SECURE_CRT_FUNCS_H__
