#define EXPORTING
#include <includes.h>


/**
 * @brief Escapes \\n and \\r \\ properly. The resulting string
 * @brief is copied in another buffer  and returned.
 * 
 * @param in The string in which to escape newlines, carriage returns and
 *           backslashes.
 * 
 * @return Parameter in, escaped or NULL if in equals NULL.
 */
ExtFunc char *
addslashes (char* in)
{
 char * ret;
 char * out;

 if (in == NULL) return NULL;

 out = malloc(strlen(in) * 2 + 1);
 bzero(out, strlen(in) * 2 + 1);
 ret = out;
 while(in[0])
 {
  if(in[0] == '\\')
  {
   out[0] = '\\'; out++;
   out[0] = '\\'; out++;
  }

  else if(in[0] == '\n')
  {
   out[0] = '\\'; out++;
   out[0] = 'n'; out++;
  }
  else if(in[0] == '\r')
  {
    out[0] = '\\'; out++;
    out[0] = 'r';  out++;
  }
  else {
	  out[0] = in[0];
	  out++;
  }
  in++;
 }
 return realloc(ret, strlen(ret) + 1);
}

/**
 * @brief Replaces escape codes (\n, \r) by the real value.
 * 
 * The resulting string is stored in another buffer
 * @see addslashes
 */
ExtFunc char *
rmslashes (char * in)
{
 char * out = malloc(strlen(in) + 1);
 char * ret = out;
 bzero(out, strlen(in) + 1);
 while(in[0])
 {
  if(in[0] == '\\')
  {
   switch(in[1])
   {
    case 'r' :
      out[0] = '\r';
      in++;
      break;
    case 'n' :
      out[0] =  '\n';
      in++;
      break;
    case '\\' :
      out[0] = '\\';
      in++;
      break;
    default :
      fprintf(stderr, "Unknown escape sequence '\\%c'\n", in[1]);
   }
  }
  else out[0] = in[0];
  in++;
  out++;
 }
 return realloc(ret, strlen(ret) + 1);
}

