#include <iostream>
#include <fstream>
#include "errno.h"

#include "Disk.h"

extern int errno;
using namespace std;

Disk::Disk (const char * filename) {

	diskSize = 0;

	if ((out = fopen(filename, "rb")) == NULL)
		out = fopen(filename, "w+b");
	else
		out = fopen(filename, "r+b");
	
	if (!out) {
		cerr<<"File: "<<filename<<" can not open for writing: "<<errno<<endl;
		return;
	}

	in = fopen(filename, "r+b");
	if (!in) {
		cerr<<"File: "<<filename<<" can not open for reading: "<<errno<<endl;
		return;
	}
}

Disk::~Disk () {

	fclose(in);
	fclose(out);
}

int Disk::read (char * n, int size, long position) {
	
	fseek(in, position, SEEK_SET);
	fread(n, 1, size, in);
	fflush(in);

	return 0;
}

int Disk::write (const char * n, int size, long position) {
	
	fseek(out, position, SEEK_SET);
	fwrite(n, 1, size, out);
	fflush(out);
	if (position == 0)
		cout<<"DISKWRITE0"<<endl;
	return 0;
}

long Disk::getFreeDiskBlock(long length) {

	//fseek (in,1,SEEK_END);
	//return ftell(in);
	
	long temp = diskSize;
	
	diskSize += length;

	//cout<<"DISK: diskSize = "<<diskSize<<endl;
	return temp;
}
