// $Id: CFileLiteracy.cc,v 1.4 2003/04/23 09:20:58 ta_muto Exp $

#include <CFileLiteracy.h>

wax::CFileLiteracy::~CFileLiteracy()
{
	if(out != NULL)	close();
	if(tempFile != NULL)	xmlFree(tempFile);
	if(tempDir != NULL)	xmlFree(tempDir);
}

bool wax::CFileLiteracy::open()
{
	tempFile = xmlStrdup(getPath());
	tempFile = xmlStrcat(tempFile, (const xmlChar*) ".temp");

	tempDir = xmlStrdup(getPath());
	tempDir = xmlStrcat(tempDir, (const xmlChar*) ".d");
	
	int count = 0;
	while(makeDir(tempDir) == false) {
		count++;
		if(count > 4)	return false;
		sleepTimer(1);
	}
	out = fopen((const char*) tempFile, "wb");
	if(out == NULL)	return false;
	return CFileReader::open();
}

bool wax::CFileLiteracy::flush()
{
	if(out != NULL) {
		fclose(out);
		out = NULL;
	}
	while(remove((const char*)getPath()) != 0) {
		//
	}
	rename((const char*)tempFile, (const char*)getPath());
	removeDir(tempDir);
	return true;
}

void wax::CFileLiteracy::unlock()
{
	if(out != NULL) {
		fclose(out);
		out = NULL;
	}
	remove((const char*)tempFile);
	removeDir(tempDir);
}
