// Bastard File System
// (C) 2007 Rene Schickbauer
//
// The Bastard File System (BFS) is a small virtual FS for Applications
// that would normally use Tarballs and/or Zipfiles but have to dynamically
// change its contents
//
// WARNING: This is still ALPHA QUALITY CODE! Use with care!
//
//
#include "bfs_rawio.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//#define RAMTESTS

#ifdef RAMTESTS
BLOCK_RAW mydata[1000];
#endif // RAMTESTS

bool hasWrittenBlock = false;

bool readRawBlock(sBFS* handle, int blockNum, BLOCK_RAW* data) {
	
#ifndef RAMTESTS
    int foffs = blockNum * 512;
    
    if(hasWrittenBlock) {
		fflush(handle->fh);
		hasWrittenBlock = false; // Ok, we flushed all pending writes
	}
    
    if(fseek(handle->fh, foffs, SEEK_SET)) {
        sprintf(handle->lastError, "Can't seek to block %d", blockNum);
        return false;
    }
    
    int bytes = fread(data->data, 1, 512, handle->fh);
    if(bytes != 512) {
        sprintf(handle->lastError, "Read error length; read %d bytes", bytes);
        return false;
    }
#else //  RAMTESTS
    memcpy(data, &mydata[blockNum], 512);
#endif //  RAMTESTS
    return true;
}
    
bool writeRawBlock(sBFS* handle, int blockNum, BLOCK_RAW* data) {
#ifndef RAMTESTS
    int foffs = blockNum * 512;
    
    if(fseek(handle->fh, foffs, SEEK_SET)) {
        sprintf(handle->lastError, "Can't seek to block %d", blockNum);
        return false;
    }
    
    int bytes = fwrite(data->data, 1, 512, handle->fh);
    if(bytes != 512) {
        sprintf(handle->lastError, "Write error length; wrote %d bytes", bytes);
        return false;
    }
    
    hasWrittenBlock = true; // Remember to flush before next read

#else // RAMTESTS
	memcpy(&mydata[blockNum], data, 512);
#endif //  RAMTESTS
    
    return true;
}

