/*
 * This code is part of Screws project.
 * Copylefted by pancake@phreaker.net at 2003
 */

#include "IO.h"
#define NEWBUFFER 1
#define BLOCKING 1

void
IO_buffer(n,s,out)
	int n;
	int s;
	int out;
{
	loop_t i,j;
	bool deadChildren=false;
	bool dead=false;
	char *b;

	char buf[65536];

	i=0;
#if BLOCKING
//fcntl(out,F_SETFL,O_NONBLOCK,1);
	while(1)
	{
		j=read(out,buf,1);
	if (j==0) 
{
	printf("EOF\n");
	exit(1);
}	
		if (j==-1)
		{
			if (waitpid(-1,0,WNOHANG))
			{
			printf("DIE\n");
			break;
			}
		printf("LESSONE\n");
			break;
			j=0;
		}
		if (j)
		{
		screws_send(s,buf,1);
//		printf("%d(%c)",j,buf[0]);
//		fflush(stdout);
		}
	}
#else
#if NEWBUFFER
	fcntl(out,F_SETFL,O_NONBLOCK,1);
	while(1)
	{
		if (!dead)
			dead=waitpid(-1,0,WNOHANG);
		j=read(out,buf+i,tcpwin-i);
		if (j>=0) { i+=j; }
		else 
		if ( dead ) goto IO_BUFFER_END;

		if (i>=tcpwin)
			{
			setHTTPCode(buf,i); // gets 1ms more... XXX should be optimized
			if (! screws_send(s,buf,i) )
				return;
			i=0;
			}
	}
	IO_BUFFER_END:
	setHTTPCode(buf,i);
	if (! screws_send(s,buf,i) )
		return;
	waitpid(-1,0,WNOHANG); // XXX strange,but useful ripper
	return;
#else
	fcntl(out,F_SETFL,O_NONBLOCK,1);
	b=(char *)malloc(tcpwin+1);

	for(i=0;;)
	{
		if (!deadChildren)
		deadChildren=waitpid(-1,0,WNOHANG);
		j=read(out,b+i,tcpwin-i); /* fill da baffah */
		//usleep(Svr.usleep); /* Smooooo the loop :) */

		if (j<0&&deadChildren)
			break;

		if (j>0) i+=j;

		if (i>=tcpwin)
		{
			setHTTPCode(b,i);
			screws_send(s,b,i);
			i=0;
		}
	}

	setHTTPCode(b,i);
	screws_send(s,b,i);

	waitpid(-1,0,WNOHANG);
	free(b);
#endif
#endif // BLOCKING
}
