#include "leafnode.h"
#include "critmem.h"

#ifdef WITH_DMALLOC
#include <dmalloc.h>
#endif

#include <string.h>

/*@null@*/ /*@only@*/ char *
getfoldedline(FILE * f, char *(*reader)(FILE *))
{
    /* what characters are considered whitespace that marks the beginning of
       continuation lines.
       WARNING: NEVER EVER list \n here! */
    static const char white[] = " \t";
    char *l1, *l2;
    int c;
    size_t len, oldlen;

    l1 = reader(f);
    if (!l1)
	return NULL;
    l2 = (char *)critmalloc((len = strlen(l1)) + 1, "getfoldedline");
    strcpy(l2, l1); /* RATS: ignore */

    /* only try to read continuation if the line is not empty 
     * and not a lone dot */
    if (*l2 && strcmp(l2, ".")) {
	for (;;) {
	    c = fgetc(f);
	    if (c != EOF) {
		ungetc(c, f);
		if (strchr(white, c)) {
		    /* join */
		    l1 = reader(f);
		    if (l1) {
			oldlen = len;
			len += strlen(l1) + 1;
			l2 = (char *)critrealloc(l2, len + 2,
						   "getfoldedline");
			l2[oldlen++] = '\n';
			strcpy(l2 + oldlen, l1); /* RATS: ignore */
		    }
		} else {
		    break;
		}
	    } else {
		break;
	    }
	}
    }
    return l2;
}

#ifdef TEST
int debug = 0;

int
main()
{
    char *f;
    while ((f = getfoldedline(stdin, getaline))) {
	puts(f);
	free(f);
    }
    return 0;
}
#endif


syntax highlighted by Code2HTML, v. 0.9.1