#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "link.h"

/*
	elimine les blancs et saut de ligne de la fin d'une chaine
  	newstr et str peuvent ˆtre la mˆme variable
	Retourne le nombre de byte eliminer au bout de la chaine
*/
int str_strip (
	const char *str,	/* Chaine a tronquer */
	char *newstr)		/* Resultat */
{
	int ret = 0;
	int len = strlen(str);
	char *pt = newstr + len-1;
	strcpy (newstr,str);
	while (len > 0 && isspace(*pt)){
		*pt-- = '\0';
		len --;
		ret ++;
	}
	return (ret);
}
/*
	Strip white char at the end of a string.
	Return the address of the last non white char + 1 (point on the '\0').
*/

char *strip_end(char *str)
{
	int len = strlen(str);
	for (str += len - 1
		; len > 0 && (isspace(*str) || *str == 26)
		; len--, str--) *str = '\0';
	return str+1;
}
	
/*
	Skip the white char in a string
*/
char *str_skip (const char *str)
{
	while (isspace(*str)) str++;
	return (char*)str;
}

/*
	strdup with error checking.
	Does not return if any error.
*/
char *strdup_err (const char *str)
{
	char *ret = strdup(str);
	if (ret == NULL){
		depmod_error ("Out of memory");
		exit (-1);
	}
	return ret;
}

/*
	Free all string in a table
*/
void tbstr_free (char *lst[], int nb)
{
	for (int i=0; i<nb; i++) free (lst[i]);
}

extern "C" char *stpcpy(char *dst, const char *src)
{
	strcpy (dst,src);
	return dst + strlen(dst);
}

/*
	Extract the name of a file (without the directory component).
*/
void path_extrname (const char *path, char *name)
{
	const char *pt = strrchr(path,'/');
	pt = pt == NULL ? path : pt + 1;
	strcpy (name,pt);
}

