/************************************************************************
 * grammer - src/io.c
 * Copyright (C) 2002 Marcello Barnaba <vjt@openssl.it>
 *
 * 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 1, 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.
 *
 * io functions . . .
 */

#include "struct.h"
#include "io.h"
#include "memory.h"

__inline void outf(char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(out, fmt, ap);
    va_end(ap);
    fflush(out);
}

char *acquire_string(int fd, char delim)
{
    char buf[32], *str = NULL;
    size_t rd = 0, strl = 0;
    fd_set rfd;

    FD_ZERO(&rfd);
    FD_SET(fd, &rfd);
    
    while(select(fd + 1, &rfd, NULL, NULL, NULL))
    {
	memset(buf, 0x0, sizeof(buf));
	if((rd = read(fileno(in), buf, sizeof(buf) - 1)) < 0)
	{
	    outf("read error\n");
	    exit(-1); /* XXX */
	    /* NOTREACHED */
	    return NULL;
	}

	str = xrealloc(str, strl + rd + 1);
	memcpy(str + strl, buf, rd);
	strl += rd;

	if(buf[rd-1] == delim)
	{
	    str[strl-1] = '\0';
	    break;
	}
    }
    return str;
}

