/* getline.c version 1.0 PA0GRI */
#include <stdio.h>
#include <ctype.h>
#include "global.h"
#include "commands.h"

/*
 *	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 *
#ifdef PROTOTYPES
getline(FILE *fp)
#else
getline(fp)
FILE *fp;
#endif
{
	char *line;
	char *contline;
	char *chrptr1;
	char *chrptr2;
	int s1,s2;
	int loop = 1;

	if(fp == NULLFILE)
		return NULLCHAR;	/* just in case */
	line = mallocw(256);		/* get buffer space */
#ifdef __GNUC__
	s1 = 0;			/* this one may be for real... */
#endif
	while(loop){
		if(fgets(line,256,fp) == NULL){
			free(line);
			return NULLCHAR;
		}
		if(line[0] == '#' || line[0] == ';')
			continue;	/* skip comment lines */
		if((s1 = strlen(line)) < 2)
			continue;	/* empty line */
		loop = 0;		/* none of above */
	}
	line[s1-1] = '\0';		/* kill nl */
	if((chrptr1 = strchr(line,';')) != NULLCHAR){
		*chrptr1 = '\0';	/* eliminate comment */
		s1 = 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(256);	/* get buffer space */
	while(loop){
		if(fgets(contline,256,fp) == NULL){
			free(line);
			free(contline);
			return NULLCHAR;
		}
		s2 = strlen(contline);
		contline[s2-1] = '\0';	/* kill nl */
        if(contline[0] == '#' || contline[0] == ';')
			continue;	/* skip comment lines */
        if((s2 = strlen(contline)) < 2)
			continue;	/* empty line */
		if((chrptr1 = strchr(contline,';')) != NULLCHAR){
			*chrptr1 = '\0';	/* eliminate comment */
			s2 = 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;
}
