/*
 * mr_string.c - New generation of string handling functions
 */

#include <stdio.h>
#include <string.h>
 
/**
 * Safe alternative to standard function strok()
 * @param instr
 * @param delims
 * @param lastpos
 * @return @p
 * @note this function allocates memory that needs to be freed by caller
 **/
char *mr_strtok(char *instr, const char *delims, int *lastpos)
{

	char *token = NULL;
	char *strptr = NULL;
	size_t pos1 = 0;
	size_t pos2 = 0;

	if (strlen(instr) <= *lastpos) {
		*lastpos = 0;
		return token;
	}

	strptr = instr + *lastpos;
	pos2 = strspn(strptr, delims);
	strptr += pos2;
	pos1 = strcspn(strptr, delims);
	token = malloc(sizeof(*token) * (pos1 + 1));
	strncpy(token, strptr, pos1);
	token[pos1] = '\0';
	*lastpos = *lastpos + pos1 + pos2 + 1;

	return token;
}


/**
 * Returns the string fed to it 'inptr' with all characters to escape given
 * in 'toesc' prepended by escaping character 'escchr'.
 * (Prepare strings for use in system() or popen() with this function.)
 * @param instr
 * @param toesc
 * @param escchr
 * @note this function allocates memory that needs to be freed by caller
 **/
char *mr_stresc(char *instr, char *toesc, const char escchr)
{

	char *inptr = NULL;
	char *retstr = NULL;
	char *retptr = NULL;
	char *escptr = NULL;
	int cnt = 0;

	inptr = instr;

	// Count how many characters need escaping.
	while (*inptr != '\0') {
		escptr = toesc;
		while (*escptr != '\0') {
			if (*inptr == *escptr) {
				// Found it, skip the rest.
				cnt++;
				break;
			}
			escptr++;
		}
		inptr++;
	}
	inptr = instr;

	retstr = (char *) malloc(strlen(inptr) + cnt + 1);
	retptr = retstr;

	// Prepend specified characters with escape character.
	while (*inptr != '\0') {
		escptr = toesc;
		while (*escptr != '\0') {
			if (*inptr == *escptr) {
				// Found it, prepend with the escape char
				*retptr = escchr;
				retptr++;
				break;
			}
			escptr++;
		}
		*retptr = *inptr;
		retptr++;
		inptr++;
	}
	*retptr = '\0';

	return retstr;
}
