/*                      QBCC Project

This source file is licensed under the GNU Lesser Public Licence which should be 
included with the distribution of this source.

*/
// OPEN & CLOSE Functions

#include "../include/stdlibh.h"
#include "../include/stringh.h"
#include "../include/file.h"


///////////////////
// OPEN function
int OPEN(string *filename, int ModeType, int *FileNumber)
{
	char filemode[8];

	
	// Do massive error checking
	if(!filename)
		return FALSE;
	if(!filename->ptr || filename->length < 1)
		return FALSE;
	if(*FileNumber < 0 || *FileNumber >= MAX_FILES)
		return FALSE;
	if(Files[*FileNumber].used)
		return FALSE;
	if(ModeType < 0 || ModeType > 8)		// Be sure to change this if you add more file opening modes
		return FALSE;



	switch(ModeType)
	{
		case FL_APPEND:  strcpy(filemode,"a");    break;
		case FL_BINARY:  strcpy(filemode,"wb");  break;
		case FL_INPUT:   strcpy(filemode,"rt");   break;
		case FL_OUTPUT:  strcpy(filemode,"wt");  break;
		default:    return FALSE;
	}

	// Open the file
	Files[*FileNumber].ptr = fopen(filename->ptr,filemode);
	if(Files[*FileNumber].ptr == NULL)
		return FALSE;
	Files[*FileNumber].used = TRUE;
	Files[*FileNumber].reclen = 0;			// ??
	Files[*FileNumber].FMode = ModeType;

	return TRUE;
}


///////////////////
// CLOSE function
void CLOSE(int *FileNumber)
{
	int n;

	if(*FileNumber == -1)
	{
		// Close All
		for(n=0;n<MAX_FILES;n++)
		{
			if(!Files[n].used)
				continue;
			if(!Files[n].ptr)
				continue;
			fclose(Files[n].ptr);
			Files[n].used = FALSE;
		}
	}
	else
	{
		// Close Single File
		if(*FileNumber < 0 || *FileNumber >= MAX_FILES)
			return;		
		if(!Files[*FileNumber].used)
			return;
		if(!Files[*FileNumber].ptr)
			return;
		fclose(Files[*FileNumber].ptr);
		Files[*FileNumber].used = FALSE;
	}
}

