#include "ctdl.h"

#ifdef WINCIT

Bool citOpen(const char *filename, CitOpenCodes mode, citFILE *cf)
	{
	int winMode;

	if (mode == CO_W || mode == CO_WB)
		{
		winMode = OF_WRITE | OF_CREATE;
		}
	else if (mode == CO_R || mode == CO_RB)
		{
		winMode = OF_READ;
		}
	else if (mode == CO_RPB)
		{
		winMode = OF_READWRITE;
		}
	else if (mode == CO_WPB)
		{
		winMode = OF_READWRITE | OF_CREATE;
		}

	cf->citType = mode;
	cf->pos = 0;
	cf->fileHandle = OpenFile(filename, &(cf->of), winMode);

	if (cf->fileHandle == -1)
		{
		if (mode == CO_A || mode == CO_AB || mode == CO_AP)
			{
			winMode |= OF_CREATE;

			cf->fileHandle = OpenFile(filename, &(cf->of), winMode);
			}

		if (cf->fileHandle == -1)
			{
			return (FALSE);
			}
		}

	if (mode == CO_A || mode == CO_AB || mode == CO_AP)
		{
		citSeek(*cf, 0, SEEK_END);
		}

	return (TRUE);
	}

int citRead(void *where, int len, int num, citFILE f)
	{
	assert(f.fileHandle >= 0);

	return (_lread(f.fileHandle, where, len * num) / len);
	}

int citWrite(void *where, int len, int num, citFILE f)
	{
	assert(f.fileHandle >= 0);

	if (f.citType == CO_A || f.citType == CO_AB || f.citType == CO_AP)
		{
		citSeek(f, 0, SEEK_END);
		}

	return (_lwrite(f.fileHandle, where, len * num) / len);
	}

int citClose(citFILE *f)
	{
	int ret = FALSE;

	if (f->fileHandle)
		{
		ret = _lclose(f->fileHandle);
		f->fileHandle = -1;
		}

	return (ret);
	}

long citSeek(citFILE f, long sw, int whence)
	{
	assert(f.fileHandle >= 0);

	return (_llseek(f.fileHandle, sw, whence));
	}


void citWinCloseTmp(citFILE *f)
	{
	assert(f->fileHandle >= 0);

	if (f->fileHandle)
		{
		f->pos = _llseek(f->fileHandle, 0, SEEK_CUR);
		_lclose(f->fileHandle);
		f->fileHandle = -1;
		}
	}

void citWinReOpen(citFILE *f)
	{
	assert(f->fileHandle == -1);

	if (f->fileHandle == -1)
		{
		f->fileHandle = OpenFile("poo", &f->of, OF_READWRITE | OF_REOPEN);
		_llseek(f->fileHandle, f->pos, SEEK_SET);
		}
	}

long citTell(citFILE f)
	{
	assert(f.fileHandle >= 0);

	if (f.fileHandle && f.fileHandle != -1)
		{
		return (_llseek(f.fileHandle, 0, SEEK_CUR));
		}
	else
		{
		return (CERROR);
		}
	}

#else

Bool citOpen(const char *filename, CitOpenCodes mode, citFILE *cf)
	{
	const char *cMode;

	switch (mode)
		{
		case CO_A:		cMode = FO_A;	break;
		case CO_AB: 	cMode = FO_AB;	break;
		case CO_AP: 	cMode = FO_AP;	break;
		case CO_R:		cMode = FO_R;	break;
		case CO_W:		cMode = FO_W;	break;
		case CO_WB: 	cMode = FO_WB;	break;
		case CO_RB: 	cMode = FO_RB;	break;
		case CO_RPB:	cMode = FO_RPB; break;
		default:
		case CO_WPB:	cMode = FO_WPB; break;
		}

	*cf = fopen(filename, cMode);

	return (*cf != NULL);
	}

#endif
