/*
 *	util_local.c
 *
 *	library for utils/make_*
 */

#include "includes.h"

#undef strchr

char *safe_strcpy(char *dest, const char *src, size_t maxlength)
{
	size_t len;

	len = strlen(src);
	if (len > maxlength)
		len = maxlength;
	memmove(dest, src, len);
	dest[len] = '\0';
	return dest;
}

BOOL next_token(const char **ptr, char *buff, const char *sep, size_t bufsize)
{
	const char *s;
	BOOL quoted;
	size_t len=1;

	s = *ptr;

	/* default to simple separators */
	if (!sep)
		sep = " \t\n\r";

	/* find the first non sep char */
	while(*s && strchr(sep,*s))
		s++;

	/* nothing left? */
	if (! *s)
		return(False);

	/* copy over the token */
	for (quoted = False; len < bufsize && *s && (quoted || !strchr(sep,*s)); s++) {
		if (*s == '\"') {
			quoted = !quoted;
		} else {
			len++;
			*buff++ = *s;
		}
	}

	*ptr = (*s) ? s+1 : s;
	*buff = '\0';

	return(True);
}

int sys_stat(const char *fname,SMB_STRUCT_STAT *sbuf)
{
	int ret;
#if defined(HAVE_EXPLICIT_LARGEFILE_SUPPORT) && defined(HAVE_OFF64_T) && defined(HAVE_STAT64)
	ret = stat64(fname, sbuf);
#else
	ret = stat(fname, sbuf);
#endif
	/* we always want directories to appear zero size */
	if (ret == 0 && S_ISDIR(sbuf->st_mode)) sbuf->st_size = 0;
	return ret;
}

FILE *sys_fopen(const char *path, const char *type)
{
#if defined(HAVE_EXPLICIT_LARGEFILE_SUPPORT) && defined(HAVE_FOPEN64)
	return fopen64(path, type);
#else
	return fopen(path, type);
#endif
}
