#include "stdafx.h"

bool SuperFile::Open(char *fname, bool forwrite)
{
	if (f) Close();
	writing=forwrite;
	f=fopen(fname,forwrite?"wb":"rb");
	return f!=NULL;
}

void SuperFile::Close()
{
	if (f) fclose(f);
	f=NULL;
}

int SuperFile::StartChunk(int id, int ver)
{
	if (writing && f)
	{	
		if (inchunk) EndChunk();
		inchunk=1;
		chunksize=0;
		chunkstart=ftell(f);		
		Write(&id,4);
		Write(&ver,4);
		Write(&chunksize,4);
	}
	if (!writing && f)
	{
		return FindChunk(id,ver);
	}
	return 0;
}

void SuperFile::EndChunk()
{
	if (f && inchunk)
	{
		inchunk=0;
		if (writing)
		{
			int cur=ftell(f);
			chunksize=cur-chunkstart;
			fseek(f,chunkstart+8,SEEK_SET);
			fwrite(&chunksize,1,4,f);
			fseek(f,cur,SEEK_SET);
		}
		else
		{
			fseek(f,chunkstart+chunksize,SEEK_SET);
		}
	}
}

int SuperFile::ReadNextChunk(int &id, int &ver)
{
	if (!writing && f)
	{
		if (inchunk) EndChunk();
		chunkstart=ftell(f);
		Read(&id,4);
		Read(&ver,4);
		Read(&chunksize,4);
		inchunk=1;
	}
	return chunksize;
}

int SuperFile::FindChunk(int id, int ver)
{
	int xid,xver;
	while (!Eof())
	{
		ReadNextChunk(xid,xver);
		if (xid==id && xver==ver) break;
		EndChunk();
	}
	if (Eof()) return 0;
	return chunksize;
}


void SuperFile::Write(void *data, int size)
{
	if (f && writing) fwrite(data,1,size,f);
}

void SuperFile::Read(void *data, int size)
{
	if (f && !writing) 
	{
		if (fread(data,1,size,f)==0)
		{
			eof=1;
		}
	}
}
