/*
 * rlgets() reads an arbitrarily long line in from the given FILE*
 *
 * arguments:
 *      string: a rlString*
 *	file:the file we're reading the line from
 *
 * returns:
 *	# of bytes in the line, or 0 if eof/error
 */

#include <string.h>
#include <malloc.h>

#include "rlstring.h"

int
rlgets(rlString *string, FILE *file)
{
    char block[200];	/* read the line in in 199 byte chunks; we allocate
			 * 200 bytes so we can have a guaranteed null byte
			 * at the end
			 */
    char *p;
    int linelen = 0;
    int size;

    block[(sizeof block)-1] = 0;
    do {
	if ( (p = fgets(block, (sizeof block)-1, file)) == 0)
	    break;
	size = strlen(block);
	if ( linelen + size >= string->alloc - 2 ) {
	    string->data = realloc(string->data, (linelen + size) * 2);
	    if ( string->data == 0 )
		return 0;
	    string->alloc = (linelen + size) * 2;
	}
	memcpy( string->data+linelen, block, size);
	linelen += size;
    } while ( ( size ? (block[size-1]) : '?') != '\n');

    string->data[linelen] = 0;
    return string->size = linelen;
} /* rlgets */


/*
 * rlputs() writes out a rlString
 */
int
rlputs(rlString *line, FILE *where)
{
    return fwrite(line->data, sizeof line->data[0], line->size, where);
}
