//
//striosck.c
//
//Functions relevant to doing string operations with files and sockets.
//
//
//-UserX 2001/11/04

#include "base/str.h"
#include "base/strio.h"
#include "base/dblock.h"
#include "file/file.h"

//read a line of text from a file.
// carriage returns are discarded.
// linefeeds indicate end of line.
char *stringReadLine(FileHandle *fh){
	int c;
	DataBlock *db = dblockEmpty("stringReadLine");
	char *buffer;

	if(fh == NULL) {
		dblockFree(db);
		return NULL;
	}

	while(!fileEOF(fh) && !fileError(fh)) {
		c = fileReadChar(fh);
		if(c == EOF) {
			break;
		}
		if(c == '\n') {
			break;
		}
		switch(c) {
		case 0:
		case '\r':
			break;
		default:
			db = dblockResize(db, db->size + 1);
			db->data[db->size] = (uint8) c;
			db->size++;
		}
	}
	db = dblockResize(db, db->size + 1);
	db->data[db->size] = 0;
	db->size++;

	buffer = stringCopy((char *)db->data);

	dblockFree(db);

	return buffer;
}

//todo: ditch this
char *stringReadLineOrEOF(FileHandle *fh) {
	int c = 0;
	DataBlock *db = dblockEmpty("stringReadLine");
	char *buffer;

	if(fh == NULL) {
		dblockFree(db);
		return NULL;
	}

	while(!fileEOF(fh) && !fileError(fh)) {
		c = fileReadChar(fh);
		if(c == EOF) {
			break;
		}
		if(c == '\n') {
			break;
		}
		switch(c) {
		case 0:
		case '\r':
			break;
		default:
			db = dblockResize(db, db->size + 1);
			db->data[db->size] = (uint8) c;
			db->size++;
		}
	}
	//if(c == EOF || feof(fh) || ferror(fh)) {
		if(db->size == 0) {
			db = dblockResize(db, db->size + 1);
			db->data[db->size] = '\x1a';
			db->size++;
		}
	//}
	db = dblockResize(db, db->size + 1);
	db->data[db->size] = 0;
	db->size++;

	buffer = stringCopy((char *)db->data);

	dblockFree(db);

	return buffer;
}

//write a string to a file.
//string will be released
void stringWriteLine(char *text, FileHandle *fh) {
	//fprintf(fh, "%s\n", text);
	fileWriteStringKeep(fh, text);
	fileWriteStringKeep(fh, "\n");
	stringFree(text);
}
