#include <stdio.h>
#include <string.h>
#include "link.h"

/*
	Read a line of a configuration file and process continuation line.
	Return buf, or NULL si eof
	Blank at the end of line are always stripped.
	Everything following comcar is a comment. The line is cut before.
*/
char *fgets_strip (
	char *buf,
	int sizebuf,
	FILE *fin,
	char contcar,		// Continuation char, generally backslash
	char comcar,		// Comment character, generally #
	int *noline,		// This will be updated and contain the line number
						// Can be NULL
	int *empty)			// Will be != 0 if the line is empty and did not
						// even hold a comment.
{
	int nocomment = 1;		// No comments found ?
	int contline=0;
	char *debut = buf;
	char *ret = NULL;
	*buf = '\0';
	*empty = 1;
	while (fgets(buf,sizebuf,fin)!=NULL){
		char *end = strip_end (buf);
		char *pt = strchr(buf,comcar);
		if (pt != NULL){
			nocomment = 0;
			*pt = '\0';
			end = strip_end (buf);
		}
		if (noline != NULL) (*noline)++;
		ret = debut;
		if (contline){
			char *pt = str_skip(buf);
			if (pt > buf+1){
				strcpy (buf+1,pt);
				buf[0] = ' ';
				end-=(int)(pt-buf)-1;
			}else if (pt == buf+1){
				buf[0] = ' ';
			}
		}
		if (end > buf && *(end-1) == contcar){
			if (end == buf+1 || *(end-2) != contcar){
				/* Continuation demand‚ */
				contline = 1;
				end--;
				*end = '\0';
				buf = end;
			}else{
				*(end-1) = '\0';
				break;
			}
		}else{
			break;
		}
	}
	*empty = debut[0] == '\0' && nocomment;
	return ret;
}		

/*
	Read a line of a configuration file and process continuation line.
	Return buf, or NULL si eof
	Blank at the end of line are always stripped.
	Everything following comcar is a comment. The line is cut before.
*/
char *fgets_strip (
	char *buf,
	int sizebuf,
	FILE *fin,
	char contcar,		// Continuation char, generally backslash
	char comcar,		// Comment character, generally #
	int *noline)		// This will be updated and contain the line number
						// Can be NULL
{
	int empty;
	return fgets_strip (buf,sizebuf,fin,contcar,comcar,noline,&empty);
}

/*
	Read a line of a configuration file and process continuation line.
	Return buf, or NULL si eof
	Blank at the end of line are always stripped.
	Everything following comcar is a comment. The line is cut before.

	Continuation character is \
	Comment character is #
*/
char *fgets_strip (
	char *buf,
	int sizebuf,
	FILE *fin,
	int *noline)		// This will be updated and contain the line number
						// Can be NULL
{
	int empty;
	return fgets_strip (buf,sizebuf,fin,'\\','#',noline,&empty);
}

