/*
    This file is part of SUPPL - the supplemental library for DOS
    Copyright (C) 1996-2000 Steffen Kaiser

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* $RCSfile: CFGI_QS.C $
   $Locker: ska $	$Name:  $	$State: Exp $

	int cfgi_quoteString(const char * const string)

	Quote the string and all quotes within.

	Return:
		NULL: out of memory
		else: pointer to quoted string

ob: cfgi_quoteString
ty: L
su: inifile/2
sh: Quote a string
lo: Quotes a string by surrounding the string with one quote before and after
	it and doubling all quotes already located within the string.\par
	If needed, the string is cached into cfgi_string.
va: NULL: if out of memory
	\item else: pointer to string
wa: The returned string is automatically destroyed, when this function
	is called next or the \subsys{inifile} is closed.
re: cfgi_string
fi: cfgi_qs.c
in:

*/

#include "initsupl.loc"

#ifndef _MICROC_
#include <stdlib.h>
#endif
#include "inifile.loc"
#include "dynstr.h"

#include "suppldbg.h"

#ifdef RCS_Version
static char const rcsid[] = 
	"$Id: CFGI_QS.C 1.4 2001/02/27 01:27:57 ska Exp ska $";
#endif

char *cfgi_quoteString(const char * const string)
{	const char *p;
	char *newstring, *q;
	int quotes;

	DBG_ENTER("cfgi_quoteString", Suppl_inifile2)

	assert(string);

	DBG_ARGUMENTS( ("str=\"%s\"", string) )

	chkHeap
	StrFree(cfgi_string);

	/* first count the number of quotes */
	quotes = 0;
	p = string - 1;
	while((p = strchr(p + 1, CFG_QUOTE)) != 0)
		++quotes;

	chkHeap
	if((newstring = malloc(strlen(string) + quotes + 3)) == 0)
		DBG_RETURN_S( 0)

	chkHeap
	/* quote the string and the quotes */
	*(q = newstring) = CFG_QUOTE;		/* leading quote */
	p = string;
#define ch quotes
	while((ch = (*++q = *p++)) != '\0')
		if(ch == CFG_QUOTE)		/* two quotes --> a single in-quote */
			*++q = CFG_QUOTE;
	*q = CFG_QUOTE;			/* trailing quote */
	q[1] = '\0';
	chkHeap

	DBG_RETURN_BS( cfgi_string = newstring)
}
