/***************************************************************************
 *   copyright           : (C) 2002 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.de                         *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

//own headers
#include <charsets.h>
#include <helper.h>
#include <gtincl.h>

//standard headers
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <iconv.h>
#include <ctype.h>

ucs4char_t* convert_from_system (char* input) {
  ucs4char_t* retval;
  size_t k = 0;
  ucs4char_t* temp;
  size_t i = 0;
  char buffer[4+1]; //buffer for \XXXX
  unsigned int counter;
  unsigned int status = 0;

  if (str_len(input) == 0) return NULL;
  temp = convert_to_internal(get_system_charset(),input,strlen(input));
  retval = mem_alloc((ucs4len(temp)+1)*sizeof(*retval),0);

  /* Now we have to handle all direct \XXXX character inputs
   */
  while (temp[i] != 0) {
    switch (temp[i]) {
    case 0x5c: // backslash is cast character
      switch (temp[i+1]) {
      case 0x6e: // 'n'
	retval[k++] = 0x0a;
	++i;
	break;
      case 0x5c: // backslash
	retval[k++] = 0x5c;
	++i;
	break;		    
      default:
	status = 1; //assume successful loop
	for (counter = 0; counter < sizeof(buffer)-1; ++counter) {
	  if (temp[i+1+counter] > (ucs4char_t)0x00 &&
	      temp[i+1+counter] <= (ucs4char_t)0x7f) {
	    if (isxdigit((int)temp[i+1+counter])) {
	      /* We can do this because Unicode is based on ASCII
	       * and we just tested for ASCII
	       */
	      buffer[counter] = (char)(temp[i+1+counter]&0x7f);
	    } else {
	      fprintf(stderr,_("%s: character %ld is not a hexdigit.\n"),
		      _("Error on text conversion to internal charset"),
		      (unsigned long)i+1+counter);
	      status = 0;
	      break;
	    }
	  } else {
	    fprintf(stderr,_("%s: character %ld is not ACSII.\n"),
		    _("Error on text conversion to internal charset"),
		    (unsigned long)i+1+counter);
	    status = 0;
	    break;
	  }
	}
	if (status == 1) {
	  buffer[counter] = 0;
	  retval[k++] = (ucs4char_t)hexstr2int(buffer,4);
	}
	i += counter;
	break;
      }
      ++i;
      break;
    default:
      retval[k++] = temp[i++];
      break;
    }
  }
  retval[k] = 0;
  mem_realloc(temp,0);

  return retval;
}
