/* Copyright (C) 1999 Beau Kuiper

   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, 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 "ftpd.h"

int readbuffer(NEWFILE *file)
{
	char inbuf[BUFFERSIZE];
	int size, oldsize = STRLENGTH(file->buffer);
	
	size = read(file->fd, inbuf, BUFFERSIZE);
	if (size == 0)
		file->eof = TRUE;
	else if (size == -1)
	{
		ERRORMSG(strerror(errno));
		file->eof = TRUE;
	}
	if (file->eof)
		return(size);
	string_cat(&(file->buffer), inbuf, size);
	string_filterbadchars_unix(&(file->buffer), oldsize);
	return(STRLENGTH(file->buffer) - oldsize);
}
	
NEWFILE *nfopen(char *filename)
{
	NEWFILE *new;
	
	/* if we get null, return null! */
	if (!filename)
		return(NULL);
		
	new = mallocwrapper(sizeof(NEWFILE));
	
	new->fd = open(filename, O_RDONLY);

	if (new->fd == -1)
	{
		freewrapper(new);
		return(NULL);
	}
			
	new->buffer = string_new();
	new->eof = FALSE;
	return(new);	
}

NEWFILE *nfdopen(int fd)
{
	NEWFILE *new = mallocwrapper(sizeof(NEWFILE));
	
	new->fd = fd;
	
	if (new->fd == -1)
	{
		freewrapper(new);
		return(NULL);
	}
			
	new->buffer = string_new();
	new->eof = FALSE;
	return(new);	
}

char *nfgetcs(NEWFILE *file, char testchar)
{
	char *bptr, *result;
	int slen;
	int bufferlen = 0;
	int nextbuflen = STRLENGTH(file->buffer);
	
	if (file->eof)
		return(NULL);

	while((bptr = strchr(STRTOCHAR(file->buffer) + bufferlen, (int)testchar)) == NULL)
	{
		bufferlen += nextbuflen;
		nextbuflen = readbuffer(file); 
		
		if (nextbuflen == 0)
		{
			bptr = STRTOCHAR(file->buffer) + STRLENGTH(file->buffer);
			break;
		} 
		else if (nextbuflen == -1)
			return(NULL);
	}
	
	/* set up the result */
	slen = bptr - STRTOCHAR(file->buffer) + 1;	
	
	result = mallocwrapper(slen + 1);
	memcpy(result, STRTOCHAR(file->buffer), slen);
	result[slen] = 0;
	
	/* fix up the buffer */
	string_dropfront(&(file->buffer), slen);

	return(result);
}

void nfclose(NEWFILE *file)
{
	close(file->fd);
	freewrapper(file->buffer);
	freewrapper(file);
}
