template <class DATA> class dataiterator;

template <class DATA>
class datafile : public fileobject
{
	friend class dataiterator<DATA>;

	struct RECORD
	{
		DATA	data;
		long	next;
	};

	void get_record(long,RECORD &);
	queue<long>	_deleted;
public:
	datafile(){};
	~datafile(){};

	void open(const char *);
	long add_data(DATA &);
	void append_data(long,DATA &);
	void remove_data(long);
};

template <class DATA>
void datafile<DATA>::open(const char *szpath)
{
	_deleted.clear();
	fileobject::open(szpath);
}

template <class DATA>
long datafile<DATA>::add_data(DATA &data)
{
	RECORD rec;
	rec.next = 0;
	rec.data = data;

	long ret;
	if ( !_deleted.empty() )
	{
		ret = _deleted.pop();
		write(&rec,ret,sizeof(RECORD));
	}
	else
	{
		ret = _size;
		append(&rec,sizeof(RECORD));
	}

	return ret;
}

template <class DATA>
void datafile<DATA>::append_data(long pos,DATA &data)
{
	RECORD temp;
	temp.next = pos;
	do
	{
		pos = temp.next;
		read(&temp,pos,sizeof(RECORD));
	}while(temp.next);

	temp.next = add_data(data);
	write(&temp,pos,sizeof(RECORD));
}

template <class DATA>
void datafile<DATA>::get_record(long pos,RECORD &rec)
{
	read(&rec,pos,sizeof(RECORD));
}

template <class DATA>
void datafile<DATA>::remove_data(long pos)
{
	RECORD temp;
	temp.next = pos;
	do
	{
		pos = temp.next;
		read(&temp,pos,sizeof(RECORD));

		_deleted.append( pos );
	}while(temp.next);
}
