// binfile - class library for files/streams - base class
// Copyright (c) 1997 Niklas Beisert
// See COPYING (GNU General Public License 2) for license

#include <dos.h>
#include <io.h>
#include "binfile.h"


binfile::binfile()
{
  reset();
}

binfile::~binfile()
{
  close();
}

void binfile::reset()
{
	fd = 0;
}


// ** high level io *********************************************************
errstat binfile::open(const char *name, int type)
{
	int _mode = O_BINARY;
	int _fd;

	if ((type & modeopen) && (type && moderead)) {
		_mode |= O_RDONLY;
	} else {
		return -1;
	}

	unsigned int ret = ::_dos_open(name, _mode, &_fd);
	if (ret != 0) {
		return -1;
	}

	fd = _fd;
	return 0;
}


errstat binfile::close()
{
	::_dos_close(fd);
	reset();
	return 0;
}


binfilepos binfile::read(void huge *buf, binfilepos len)
{
	binfilepos pos = 0;
	unsigned int nread;

	for (pos = 0; pos < len; pos += nread) {
		unsigned ret = ::_dos_read(fd, (char huge *)buf + pos,
			(len - pos) > 65535 ? 65535 : (unsigned int)(len - pos), &nread);
		if (ret != 0 || nread == 0) return 0;
	}
	return pos;
}


binfilepos binfile::seek(binfilepos p)
{
	return ::lseek(fd, (off_t)p, SEEK_SET);
}

binfilepos binfile::length()
{
	return (binfilepos)::lseek(fd, 0, SEEK_END);
}
