/*
 *   Pure Data Packet header file. String packet implementation.
 *   Copyright (c) by Tom Schouten <tom@zwizwa.be>
 *
 *   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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <pf/packet.h>
#include <pf/symbol.h>
#include <pf/stream.h>
#include <pf/type.h>
#include <pf/forth.h>
#include <pf/mem.h>
#include <pf/debug.h>
#include <pf/list.h>
#include <pf/string.h>
#include <pf/plugin.h>
#include <pf/stack.h>


/*
  FIXME:
  An ambiguous situation exists if a string contains zero bytes
  and is used as a Cstring in library code. What to do here?
*/

/*
  NOTE: strings are slow. (abundant malloc and realloc). this might not 
  work out well for large strings.
*/

/*
  API changed.
  when a string is freshly allocated/reused, it does NOT contain a buffer.
  i.e. s->data == NULL
*/



static pf_class_t *string_class = 0;

static inline pf_string_t* _string(pf_header_t *header){
    if (!header) return 0;
    if (header->type != PF_STRING) return 0;
    return (pf_string_t *)header;
}

char *pf_string_allot(pf_string_t *s, int size){
    PF_ASSERT(s);
    PF_ASSERT(pf_string_data(s));
    PF_ASSERT(pf_string_size(s) >= 0);
    PF_ASSERT((pf_string_size(s) + size) >= 0); // can't free beyond start.
    PF_ASSERT(pf_string_data(s)[pf_string_size(s)] == 0); // terminator check
    PF_ASSERT(pf_string_size(s) < s->buf_size); // buf size check

    // realloc if necessary
    int req_size = pf_string_size(s) + size + 1;
    if (req_size > s->buf_size){
	while (req_size > s->buf_size){
	    s->buf_size *= 2; // double it
	}
	s->super.data  = pf_realloc(pf_string_data(s), s->buf_size);
    }

    // allot chunk
    char *here = pf_string_data(s) + pf_string_size(s);
    s->super.data_size  += size;
    pf_string_data(s)[pf_string_size(s)] = 0; // c string termination
    return here;
}

// unix write semantics (won't fail)
int pf_string_write(pf_string_t *string, char *src, int size){
    void *dst = pf_string_allot(string, size);
    PF_ASSERT(dst);
    if (!dst) return e_internal;
    memcpy(dst, src, size);
    return size;
}

char *pf_packet_string_allot(pf_packet_t p, int size){
    pf_string_t *s = _string(p);
    return pf_string_allot(s, size);
}




/* create a string packet containing the string
   pointed to by c. this buffer should be freeable with libc free
*/
pf_packet_t pf_packet_string_using_buffer(char *c, int total_size, int used_size){

    pf_string_t *s = 0;
    
    PF_ASSERT(string_class); 
    PF_ASSERT(c);         
    PF_ASSERT(total_size > 0);
    PF_ASSERT(used_size >= 0);
    PF_ASSERT(used_size < total_size);

    /* create/reuse packet wrapper */
    if (!(s = (pf_string_t *)pf_factory_newpacket(pf_symbol("string")))) {
	PF_ASSERT(0);
	pf_dealloc(c);
	return 0;
    }

    /* fill struct */
    PF_ASSERT(pf_string_data(s) == 0);
    s->super.data = c;
    s->super.data_size = used_size;
    s->buf_size = total_size;
    pf_string_data(s)[used_size] = 0; // terminate

    return (pf_packet_t)s;
}

/* same as above, but make a copy first */
pf_packet_t pf_packet_string_copy_cstring(char *c){
    PF_ASSERT(c);
    char *s;
    int buf_size = strlen(c) + 1;
    s = pf_alloc(buf_size);
    strcpy(s, c);
    return pf_packet_string_using_buffer(s, buf_size, buf_size-1);
}



/* create a string packet using printf formatting
   this is the 'real string' constructor 

   the main one is for usage as generic buffer
*/

/*
int pf_packet_stringf(char *fmt, ...){
    char *string = 0;
    int len = 0;
    va_list ap;
    va_start(ap, fmt);
    vasprintf(&string, fmt, ap);
    va_end(ap);
    len = strlen(string)+1;
    PF_ASSERT(string);
    PF_ASSERT(len);
    int p = string_using_buffer(string, len);
    PF_ASSERT(-1 != p);
    return p;
}
*/

/* replacement for vasprintf */

/*
snprintf:
 Return value
       Upon  successful  return,  these  functions  return the number of characters printed (not
       including the trailing '\0' used to end output to strings).  The functions  snprintf  and
       vsnprintf do not write more than size bytes (including the trailing '\0').  If the output
       was truncated due to this limit then the return value is the number  of  characters  (not
       including  the trailing '\0') which would have been written to the final string if enough
       space had been available. Thus, a return value of size or more means that the output  was
       truncated.  (See  also below under NOTES.)  If an output error is encountered, a negative
       value is returned.

*/

pf_packet_t pf_packet_vstringf(char *fmt, va_list ap){
    /* as far as i understand, va_copy is necessary on archs
       that don't pass the arguments on the stack.. seemed to crash
       on PPC without it */
    
    /* get size */
    va_list aq;
    va_copy(aq, ap);
    int len = vsnprintf(0, 0, fmt, aq);  // pf_post("required length = %d", len);
    va_end(aq);

    if (len < 0) return 0;
	

    /* alloc + print : can't alloc strings on C stack since it's
       probably too small for large strings. */
    //char tmp[len+1];

    int bufsize = len+1;
    char *tmp = pf_alloc(bufsize);
    memset(tmp, 0, bufsize);

    len = vsprintf(tmp, fmt, ap);              // pf_post("result = %s", tmp);
    if (len < 0) {
	pf_dealloc(tmp);
	return 0;
    }

    return pf_packet_string_using_buffer(tmp, bufsize, len);
}

pf_packet_t pf_packet_stringf(char *fmt, ...){
    pf_packet_t p = 0;
    va_list ap;
    va_start(ap, fmt);
    p = pf_packet_vstringf(fmt, ap);
    va_end(ap);
    return p;
}

static int instr(char *string, char c){
    int index = 0;
    while(string[index]){
	if (c == string[index]) return index;
	index++;
    }
    return -1;
}





/* post quoted : unparse */
static pf_error_t header_string_write(pf_string_t *s, pf_string_t *string)
{
    pf_error_t e;
    char *c;
    char *c_endx;
    PF_ASSERT(s->super.type == PF_STRING);
    c = DATA(s);
    PF_ASSERT(c);
    c_endx = c + pf_string_size(s);

    if (e = pf_string_printf(string, "\"")) return e;
    while (c < c_endx){
	char special[] = {'\n', '\t', '"', '\\', 0};
	char code[]    = {'n', 't', '"', '\\', 0};
	int i = instr(special, c[0]);
	if (i >= 0){
	    if (e = pf_string_printf(string, "\\%c", code[i])) return e;
	    c++;
	}
	else if (c[0] < 32) {
	    if (e = pf_string_printf(string, "\\x%02x", ((int)*c++) & 0xff)) return e; // FIXME: can't parse these yet

	}
	else {
	    if (e = pf_string_printf(string, "%c", *c++)) return e;
	}
    }

    return pf_string_printf(string, "\"");
}


/* literal */
static pf_error_t string_printhex(pf_string_t *string, char *data, int size){
    int i;
    pf_error_t e;
    for (i = 0; i<size; i++){
	if (!(i & 0xf)) 
	    if (e = pf_string_printf(string, "\n%08x ", i)) 
		return e;
	if (!(i & 0x7)) 
	    if (e = pf_string_printf(string, " ", i)) 
		return e;
	if (e = pf_string_printf(string, "%02x ", data[i] & 0xff)) 
	    return e;
    }
    return pf_string_printf(string, "\n");
}


/* human readable representation */
static pf_error_t header_string_report(pf_string_t *s, pf_string_t *string)
{
    // FIXME: what if string contains zero characters?
    
    PF_ASSERT(s->super.type == PF_STRING);
    PF_ASSERT(DATA(s));

    // if string contains zero or >128 characters, it will be printed
    // in hexdump -C style, otherwize just as a quoted string.

    int i,n = pf_string_size(s);
    int ascii = 1;
    for (i=0; i<n; i++){
	if ((!pf_string_data(s)[i]) || (pf_string_data(s)[i] & 0x80)){
	    ascii = 0;
	    break;
	}
    }
    
    if (ascii){
	return header_string_write(s, string);
    }
    else {
	return string_printhex(string, pf_string_data(s), pf_string_size(s));
    }
}

static pf_error_t header_string_print(pf_string_t *s, pf_string_t *string){
    PF_ASSERT(s->super.type == PF_STRING);
    PF_ASSERT(DATA(s));
    pf_string_write(string, DATA(s), pf_string_size(s));
    EXIT;
}





/* get string */
char *pf_packet_string_data(pf_packet_t packet)
{
    pf_string_t *s = _string(packet);
    if (!s) return 0; // not a string, return null pointer
    PF_ASSERT(pf_string_data(s));
    return pf_string_data(s);
}


/* get used size
   this is the number of characters, excluding the trailing zero.
 */
int pf_packet_string_size(pf_packet_t packet)
{
    pf_string_t *s = _string(packet);
    if (!s) return 0; // not a string, return zero
    PF_ASSERT(pf_string_data(s));
    return pf_string_size(s);
}

/* CLASS methods */

/* retired strings have their buffers stripped. what this means is:
 * strings are really just a wrapper around malloc, meaning, they are
 * not really reusing their data. so if you want predictable
 * performance, you cannot use strings. there's really no way around
 * this, since hreusing the buffers could lead to huge memory
 * inefficiencies.
 */
static void string_sleep(pf_string_t *s){
    PF_ASSERT(DATA(s));
    PF_ASSERT(s->buf_size);
    //pf_post("deadstring: %s", pf_string_data(s));
    pf_dealloc(pf_string_data(s));
    s->super.data = 0;
    s->super.data_size = 0;
    s->buf_size = 0;
}

/* create an empty string shell */
static pf_packet_t string_factory(pf_list_t *l){

    /* create packet */
    pf_string_t *s = 0;
    if (!(s = (pf_string_t *)pf_packet_create(PF_STRING, sizeof(pf_string_t), 0))){
	PF_ASSERT(0 && PF_STRING);
	return 0;
    }
    s->super.desc = pf_symbol("string");
    s->super.theclass = string_class;

    /* fill it */
    s->buf_size = 0;        // set lower bound on buffer size
    
    return (pf_packet_t)s;
}

/* wakeup a string */
static void string_wakeup(pf_string_t *s){
    PF_ASSERT(pf_string_data(s) == 0);
}

/* copy string */
/* static void string_copydata(pf_header_t *dst_header, pf_header_t *src_header){ */
    
/*     pf_string_t *dst_string = pf_rawpacket_subheader(dst_header); */
/*     pf_string_t *src_string = pf_rawpacket_subheader(src_header); */

/*     PF_ASSERT(!dst_string->super.data) */
/*     PF_ASSERT(src_string->super.data) */
    
/*     int size = src_string->super.data_size; */
/*     char *src = src_string->super.data; */
/*     char *dst = pf_alloc(size+1); */

/*     // FIXME: share code */
/*     dst_string->super.data = dst; */
/*     dst_string->buf_size = size+1; */
/*     dst_string->super.data_size = size; */
/*     memcpy(dst, src, size+1); */
/* } */


/* STACK WORDS */

static PF_PRIMITIVE(string_size)
{
    pf_string_t *string = 0;
    int size = 0;
    CHECK1(a_packet);
    string = _string(ARG0->w.w_packet);
    if (!string) return e_type;
    pf_list_push(s, a_int, (pf_word_t)(int)string->super.data_size);
    EXIT;
}


pf_packet_t pf_packet_string_cat(pf_packet_t left, pf_packet_t right)
{
    pf_string_t *string_left, *string_right;
    if (!(string_left  = _string(left))) return 0;
    if (!(string_right = _string(right))) return 0;
    return pf_packet_stringf("%s%s", string_left->super.data, string_right->super.data);
}

static PF_PRIMITIVE(string_cat)
{
    CHECK2(a_packet, a_packet);
    pf_packet_t packet = pf_packet_string_cat(ARG1->w.w_packet,
					      ARG0->w.w_packet);
    if (!packet) return e_type;
    DROP1;
    DROP1;
    PUSH_PACKET(packet);
    EXIT;
}
static PF_PRIMITIVE(string_equals)
{
    pf_string_t *string1 = 0;
    pf_string_t *string2 = 0;
    int flag;
    CHECK2(a_packet, a_packet);
    if (!(string1 = _string(ARG1->w.w_packet))) return e_type;
    if (!(string2 = _string(ARG0->w.w_packet))) return e_type;
    if (string1 == string2) {flag = -1; goto gotflag;}
    if (string1->super.data_size != string2->super.data_size) {flag = 0; goto gotflag;}
    if (strcmp (string1->super.data, string2->super.data) == 0) {flag = -1; goto gotflag;}
    flag = 0;

  gotflag:
    DROP1;
    DROP1;
    PUSH_INT(flag);
    EXIT;
}

// ( atom string -- interpolated.string )
// it interpolates and formats just one atom, the rest can be done with concatenation
// TODO add a list interpolation.
// (i.e.: scan the number of % characters, and make sure there are that many args..

static PF_PRIMITIVE(string_interpolate) {
    CHECK1(a_packet);
    char *format = STRING(ARG0);
    if (!format) return e_type;
    pf_atom_t *a = ARG1;
    if (!a) return e_underflow;
    pf_packet_t result = 0;

    if (a->t == a_float){
	double d = a->w.w_float;
	result = pf_packet_stringf(format, d);
	if (!result) return e_internal;
    }
    else {
	void *thing = a->w.w_pointer;
	result = pf_packet_stringf(format, thing);
	if (!result) return e_internal;
    }
    
    DROP1;
    DROP1;
    PUSH_PACKET(result);
    EXIT;
}

pf_packet_t pf_packet_string_buffer(int size){
    return pf_packet_string_using_buffer(pf_alloc(size+1),
					 size+1, 0);
}



// convert a string to pure ascii 32:127
#define PRINT(xxx) {pf_string_allot(dst_string,1)[0] = xxx;}
static PF_PRIMITIVE(string_sanitize) {
    CHECKN(1);
    pf_string_t *src_string = PACKET_TYPE(ARG0, PF_STRING);
    pf_packet_t p = pf_packet_string_buffer(src_string->super.data_size);
    PUSH_PACKET(p);
    pf_string_t *dst_string = PACKET_TYPE(ARG0, PF_STRING);
    
    int i, c;
    for (i=0; i<src_string->super.data_size; i++){
	c = pf_string_data(src_string)[i];	
	if (0) {}
	//else if (c == '\\') { PRINT('\\'); PRINT('\\'); }
	//else if (c == '\n') { PRINT('\\'); PRINT('n'); }
	//else if (c == '\t') { PRINT('\\'); PRINT('t'); }
	else if ((c < 32) || (c>127)) 
        //{ PRINT('\\'); PRINT('f'); PRINT('f'); }
        { PRINT(' '); }
	    
	else PRINT(c);
    }
    NIP1; EXIT;
}


static PF_PRIMITIVE(string_to_list) {
    CHECK1(a_packet);
    pf_string_t *string = _string(ARG0->w.w_packet);
    pf_list_t *l = pf_list_new();
    PUSH_LIST(l);
    int i;
    for (i=0; i<string->super.data_size; i++){
	pf_list_queue(l, a_int, (pf_word_t)(pf_string_data(string)[i] & 0xff));
    }
    NIP1; EXIT;
}


static void _forth_word(char *name, pf_forth_primitive_t word){ 
    pf_vm_add_primitive(pf_forth_vm(), pf_symbol(name), word); 
}
static void _poly_word(char* polyname, char *name, pf_forth_primitive_t word){
    _forth_word(name, word);
}



// run before forth setup
void pf_string_setup(void)
{
    /* setup the fob packet class */
    string_class = pf_class_new(pf_symbol("string"), string_factory);
    pf_class_set_cleanup(string_class,  (pf_method_pheader_t)string_sleep);
    pf_class_set_sleep(string_class,  (pf_method_pheader_t)string_sleep);
    pf_class_set_print(string_class, (pf_method_pheader_string_t)header_string_print);
    pf_class_set_write(string_class, (pf_method_pheader_string_t)header_string_write);
    pf_class_set_report(string_class, (pf_method_pheader_string_t)header_string_report);
    //pf_class_set_copydata (string_class, string_copydata);
    pf_class_set_wakeup(string_class,  (pf_method_pheader_t)string_wakeup);
}

// run after forth setup
PF_PRIMITIVE(pf_forth_string_setup)
{
    // no copy method: strings are immutable: all ops are out of place

    /* setup string manip forth words */
    PF_REGISTER_FUNCTION(string_to_list, "string>list", "( string -- list )\tConvert a string to a list of integers.");
    PF_REGISTER_FUNCTION(string_size,    "string:size", "( string -- string size )");
    PF_REGISTER_FUNCTION(string_equals,  "string:=",    "( string string -- bool )");
    PF_REGISTER_FUNCTION(string_cat,     "string:concat", "( string string -- string )\tConcatenate strings.");
    PF_REGISTER_FUNCTION(string_interpolate, "string:%","( thing formatstring -- string )\tFormat an atom into a string. (printf)");
    PF_REGISTER_FUNCTION(string_sanitize, "sanitize", "( string -- string )\tSanitize a string: output only ASCII 32:127, convert all other to space.");
    EXIT;
}
