/* -------------------------------------------------------------------- */
/* SMS Client, send messages to mobile phones and pagers		*/
/*									*/
/* fread.c								*/
/*									*/
/*  Copyright (C) 1997,1998,1999 Angelo Masci				*/
/*									*/
/*  This library is free software; you can redistribute it and/or	*/
/*  modify it under the terms of the GNU Library General Public		*/
/*  License as published by the Free Software Foundation; either	*/
/*  version 2 of the License, or (at your option) any later version.	*/
/*									*/
/*  This library is distributed in the hope that it will be useful,	*/
/*  but WITHOUT ANY WARRANTY; without even the implied warranty of	*/
/*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU	*/
/*  Library General Public License for more details.			*/
/*									*/
/*  You should have received a copy of the GNU Library General Public	*/
/*  License along with this library; if not, write to the Free		*/
/*  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.	*/
/*									*/
/*  You can contact the author at this e-mail address:			*/
/*									*/
/*  angelo@styx.demon.co.uk						*/
/*									*/
/* -------------------------------------------------------------------- */
/* $Id$
   -------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>

#include "fread.h"
#include "error.h"
#include "logfile/logfile.h"

/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
char *slurp_file(char *filename, int *filelen)
{
	FILE	*fp;
	char 	*query_string;

	int 	total_read, 
		len, 
		max_len,
		bytes_read;


	fp = fopen(filename, "rb");
	if (fp == NULL)
	{
		lprintf(LOG_ERROR, "Opening file '%s'\n", filename);
		return NULL;
	}

	query_string = (char *)malloc(sizeof(char) * (BLK_SIZE +1));
	if (query_string == NULL)
	{
		lprintf(LOG_ERROR, "malloc() failed\n");
		exit(EMALLOC);
	}


	total_read = 0;
	len        = BLK_SIZE;
	max_len    = BLK_SIZE;

	bytes_read = fread(&query_string[total_read], 1, len, fp);
	while(bytes_read != 0)
	{	
		len        -= bytes_read;
		total_read += bytes_read;

		if (len == 0)
		{	
			query_string = (char *)realloc(query_string, sizeof(char) * (max_len + BLK_SIZE +1));
			if (query_string == NULL)
			{	return NULL;
			}

			len      = BLK_SIZE;
			max_len += BLK_SIZE;
		}

		bytes_read = fread(&query_string[total_read], 1, len, fp);
	}

	if (!feof(fp))
	{
		lprintf(LOG_ERROR, "Expecting EOF\n");
		free(query_string);
		return NULL;
	}

	fclose(fp);

	*filelen = total_read;
	return query_string;
}
