/*
   File: rtsesc.c
   Handles backslash escapes in strings

   Copyright 2005 Radboud University of Nijmegen
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
 
   This program 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 General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

   CVS ID: "$Id: rtsesc.c,v 1.6 2005/12/07 13:52:48 marcs Exp $"
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */

/* standard includes */
#include <stdio.h>
#include <errno.h>
#include <string.h>

/* libabase includes */
#include <abase_error.h>
#include <abase_memalloc.h>

/* local includes */
#include "rtsesc.h"

/*---------------------------------------------------------------------------
// returns a copy of src with some backslash escapes added
//      e.g. "abc"def\ghi" becomes "abc\"def\\ghi"
// Currently used to format affix names, terminal names (unused?),
//	text affixes, regexp patterns (so rtstrelinp can read -G output).
// - escapes linefeed, return, tab as \n, \r, \t
// - escapes other control chars (1..31) as octal (e.g. ctrl-g becomes \007)
//	(char 0 is end of string)
// - inserts a \ before: \ "
// does _not_ insert a \ before: - [ ]	(makes regexps look misleadingly)
// - inserts a \ before a - at begin or end of string, other -'s left plain
//-------------------------------------------------------------------------*/
char *dupstr_escaped (char const *src)
{
    /* space requirement is generally an overkill */
    char *buf = (char *) abs_malloc (strlen(src) * 4 + 1, "dupstr_escaped");
    char *ndst = buf;

    if (*src == '-') {
	*ndst = '\\'; *++ndst = *src++; ndst++;
    }
    while (*src) {
	switch (*src) {
	    case '\n': *ndst = '\\'; *++ndst = 'n'; break;
	    case '\r': *ndst = '\\'; *++ndst = 'r'; break;
	    case '\t': *ndst = '\\'; *++ndst = 't'; break;
	    case '\\': *ndst = '\\'; *++ndst = *src; break;
	    case '"': *ndst = '\\'; *++ndst = *src; break;
	    case '-':
		if (!src[1]) {	/* this - is last char */
			*ndst = '\\'; *++ndst = *src; break;
		}
	    default:
		if ((*src > 0) && (*src < ' ')) {
		    sprintf(ndst, "\\%03o", *src);
		    ndst += 3; /* fourth added outside switch */
		} else {
		    *ndst = *src;
		}
	}
	ndst++;
	src++;
    }
    *ndst = '\0';
    return (buf);
}
