#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include "lib.h"
#define DMID 17
#include "debug.h"
#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE (!FALSE)
#endif

#include "memfile.h"
int mem_have(IMEM *f, int len)
{
	int want;
	int have; 
	if (f->at >= f->used) {
		f->iseof = TRUE;
	}
	if (f->iseof) return 0;
	want = len;
	have = f->used - f->at; 
	if (have < want) want = have; 
	return want;	
}
char *mem_fgets(char *data, int len, IMEM *f)
{
	int want;
	int i;
	char *start=data;
	char *s;
	len--; // leave space for terminating null.  
	want = mem_have(f,len);
	//printf("Want %d %d   at=%d used=%d\n",want,len,f->at,f->used);
	if (want<=0) return NULL; 

	// Search for a 'lf' characater
	s = f->data+f->at;
	for (i=0; i<want; i++,s++) {
		f->at++;
		if (i>=len) break; 
		*data++ = *s;
		if (*s=='\n') break;
	}
	*data++ = 0; // add terminating null. 
//	printf("Got (%s) len %d\n",start,lib_strlen(start));
	*data = 0;
	return start;
}
int mem_fclose(IMEM *f)
{
	free(f->data);
	f->data = NULL;
	free(f);
	return TRUE;
}
int mem_fseek(IMEM *f, int x)
{
	if (x<0) x = 0;
	if (x>=f->used) x = f->used;
	f->at = x;
	f->iseof=FALSE;
	if (x>=f->used) f->iseof = TRUE;
	return x;
}
int mem_fread(IMEM *f,char *bf, int len)
{
	int want; 
	int from = f->at;
	want = mem_have(f,len);
	if (want<=0) {
		f->iseof = TRUE;
		return 0;
	}
//void *safe_memcpy_real(void *dst, const void *src, int bytes, void *start, int bfsz, char *file, int line)
	safe_memcpy(bf,f->data+f->at,want,bf,len);
	f->at += want;
	bf[want] = 0;
//	if (f->at >= f->used) f->iseof = TRUE;

	return want;
}
int mem_fwrite(IMEM *f, char *bf, int len)
{
	if (len + f->at > f->alloced) return -1;
	safe_memcpy(f->data+f->at,bf,len,f->data,f->alloced);
	f->at += len; 
	if (f->used < f->at) f->used = f->at;
	return len;
}
int mem_feof(IMEM *f)
{
	return f->iseof;
}






// space to avlid collision in logging. 
IMEM *mem_fopen(int sz)
{
	IMEM *m;
	m = calloc(1,sizeof(IMEM));
	m->data = calloc(1,sz+1);
	m->alloced = sz;
	return m;	
}



