/*
 * Copyright (C) 1996 by Chris Johnson.  All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear in all
 * copies and that both that copyright notice and this permission
 * notice appear in supporting documentation.  If more than a few
 * lines of this code are used in a program which displays a copyright
 * notice or credit notice, the following acknowledgment must also be
 * displayed on the same screen: "This product includes software
 * developed by Chris Johnson for use in the QuakeDef Tools package."
 * THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESSED OR IMPLIED
 * WARRANTY.
 *
 * (Thanks to Raphael Quinet for this nifty disclaimer!)
 */

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

#include "fileutil.h"

//	Returns: 1 if file exists
//			 0 if file does not exist
int	fexist(const char *filename)
{
	FILE *test;

	if ((test = fopen(filename, "rb")) == NULL)
	{
		fprintf(stderr,
				"\nError -- The following file could not be found:");
		fprintf(stderr, "\n%s\n", filename);
		return (0);
	}

	fclose(test);

	return (1);
}

// Returns: Pointer to file that was opened
//		    NULL if there was a problem
FILE *safeopen(const char *filename, const char *mode)
{
	FILE *fp;

	if ((fp = fopen(filename, mode)) == NULL)
	{
		fprintf(stderr, "\nError -- Could not ");

		if (strchr(mode, 'r') || strchr(mode, 'a'))
			fprintf(stderr, "open ");
		else
			fprintf(stderr, "create ");

		fprintf(stderr, "the following file:");
		fprintf(stderr, "\n%s\n", filename);
	}

	return (fp);
}

// Safe but not descriptive
// Returns: EOF on EOF
//			0 otherwise
int copy(FILE *dest, FILE *src, unsigned long len)
{
	char buffer[BLOCK_SIZE];
	long num_chunks;
	int	 last_chunk;

	num_chunks = len / BLOCK_SIZE;
	last_chunk = (int)(len % BLOCK_SIZE);

	for (; num_chunks > 0; num_chunks--)
	{
		if (fread(buffer, sizeof(char) * BLOCK_SIZE, 1, src) != 1)
			return (EOF);
		if (fwrite(buffer, sizeof(char) * BLOCK_SIZE, 1, dest) != 1)
			return (EOF);
	}

	if (last_chunk)
	{
		if (fread(buffer, sizeof(char) * last_chunk, 1, src) != 1)
			return (EOF);
		if (fwrite(buffer, sizeof(char) * last_chunk, 1, dest) != 1)
			return (EOF);
	}

	return (0);
}