/*******************************************************************************

  Copyright(c) 2003-2004 Aurelien Reynaud.

  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 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.

  The full GNU General Public License is included in this distribution in the
  file called COPYING.

*******************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "ggiterm.h"
#include "terminal.h"
#include "debug.h"

#include <string.h>


unsigned char buffer[BUFFER_SIZE];
size_t buffer_size = 0;


int buffer_send_char (wchar_t charcode)
{
	size_t length = 1;
	int err = 0;
#ifdef MULTIBYTE
	char tmpbuf[MB_CUR_MAX];
#endif
	
	debug (DEBUG_FUNCTION, "Entering");
#ifdef MULTIBYTE
	wctomb (NULL, charcode); /* reset internal state b/c not thread safe */
	length = wctomb (tmpbuf, charcode);
#endif

	if (length <= BUFFER_SIZE - buffer_size) {	
#ifdef MULTIBYTE
	memcpy (buffer+buffer_size, tmpbuf, length);
#else
	buffer[buffer_size] = (unsigned char)(charcode & 0xFF);
#endif
	buffer_size += length;
	} else {
		debug (DEBUG_INPUT, "Not enough free space in internal buffer");
		err = 1;
	}
	
	debug (DEBUG_INPUT, "Internal buffer: [%d/%d]",
	                    (int)buffer_size,
	                    BUFFER_SIZE);
	debug (DEBUG_FUNCTION, "Leaving");
	return err;
}

int buffer_send_string (char* buf)
{
	size_t length;
	int err = 0;
	
	debug (DEBUG_FUNCTION, "Entering");
	length = strlen (buf);
	if (length <= BUFFER_SIZE - buffer_size) {
		memcpy (buffer+buffer_size, buf, length);
		buffer_size += length;
	} else {
		debug (DEBUG_INPUT, "Not enough free space in internal buffer");
		err = 1;
	}
	debug (DEBUG_INPUT, "Internal buffer: [%d/%d]",
	                    (int)buffer_size,
	                    BUFFER_SIZE);
	debug (DEBUG_FUNCTION, "Leaving");
	return err;
}

void buffer_get_and_reset (unsigned char **buf, size_t *size)
{
	*buf = buffer;
	*size = buffer_size;
	buffer_size = 0;
}
