/* getline.c version 1.0 PA0GRI */
#include "global.h"
#include "commands.h"

#if !defined(_lint)
static char rcsid[] OPTIONAL = "$Id: getline.c,v 1.8 1996/08/29 12:11:16 root Exp $";
#endif

/*
 *	getline()
 *	to read a line from a domain file and return a usefull line
 *	completely assembled (if multy line)
 *	It skips any connent lines. It follows rfc 1133 , 1134 , 1135 , 1136.
 */
char *
getline (FILE * fp)
{
char *line;
char *contline;
char *chrptr1;
char *chrptr2;
int s1 = 0, s2;
int loop = 1;

	if (fp == NULLFILE)
		return NULLCHAR;/* just in case */
	line = mallocw (1024);	/* get buffer space */
	while (loop) {
		if (fgets (line, 1023, fp) == NULL) {
			free (line);
			return NULLCHAR;
		}
		if (line[0] == '#' || line[0] == ';')
			continue;	/* skip comment lines */
		if ((s1 = (int) strlen (line)) < 2)
			continue;	/* empty line */
		loop = 0;	/* none of above */
	}
	line[s1 - 1] = '\0';	/*lint !e771 * kill nl */
	if ((chrptr1 = strchr (line, ';')) != NULLCHAR) {
		*chrptr1 = '\0';/* eliminate comment */
		s1 = (int) strlen (line);	/* recompute line size */
	}
	if ((chrptr1 = strchr (line, '(')) != NULLCHAR) {	/* continuation */
		*chrptr1 = ' ';	/* replace with space */
		if ((chrptr2 = strchr (line, ')')) != NULLCHAR) {	/* continuation */
			*chrptr2 = ' ';	/* replace with space */
			return line;	/* complete line */
		}
		loop = 1;
	}
	contline = mallocw (1024);	/* get buffer space */
	while (loop) {
		if (fgets (contline, 1023, fp) == NULL) {
			free (line);
			free (contline);
			return NULLCHAR;
		}
		s2 = (int) strlen (contline);
		contline[s2 - 1] = '\0';	/* kill nl */
		if (contline[0] == '#' || contline[0] == ';')
			continue;	/* skip comment lines */
		if ((s2 = (int) strlen (contline)) < 2)
			continue;	/* empty line */
		if ((chrptr1 = strchr (contline, ';')) != NULLCHAR) {
			*chrptr1 = '\0';	/* eliminate comment */
			s2 = (int) strlen (contline);	/* recompute line size */
		}
		chrptr1 = mallocw ((unsigned) (s1 + s2 + 2));
		sprintf (chrptr1, "%s %s", line, contline);
		free (line);
		line = chrptr1;
		if ((chrptr2 = strchr (line, ')')) != NULLCHAR) {	/* continuation */
			*chrptr2 = ' ';	/* replace with space */
			loop = 0;
		}
	}
	free (contline);
	return line;
}
