#include <stdio.h>
#include <xil/xil.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "memmap.h"


void openfile(MFILE* memfile, char* fname)
{
    int fd;
    Xil_unsigned8 *fp;
    struct stat buf;
  
    if ((fd = open(fname, O_RDONLY)) < 0) {
        /* XILERROR(OPEN); */
        fprintf(stderr, "ERROR: failed to open %s file.\n", fname );
        exit(-1);
    }
    fstat(fd, &buf);
    fp = (Xil_unsigned8 *) mmap(0, (size_t)buf.st_size, PROT_READ,
        MAP_SHARED, fd, (off_t)0);
    if ((int)fp == -1) {
        /* XILFATALERROR(MMAP); */
        fprintf(stderr, "ERROR: mmap failed\n");
        exit(-1);
    }
    memfile->dptr = fp;
    memfile->start = fp;
    memfile->fd = fd;
    memfile->len = (int) buf.st_size;
}

void init_memfile( MFILE* memfile )
{
    memfile->dptr = NULL;
    memfile->start = NULL;
    memfile->fd = 0;
    memfile->len = 0;
    memfile->currentFrame = 0;
    memfile->mstart = NULL;
    memfile->mlen = 0;
}

void detach_file( MFILE* memfile )
{
    close(memfile->fd);
    if (munmap((caddr_t) memfile->start, memfile->len) == -1) {
        /* XILFATALERROR(MUNMAP); */
        fprintf(stderr, "ERROR: munmap failed in detach_file\n");
    }
    memfile->start = 0;
    memfile->len = 0;
    memfile->fd = 0;
}

void attach_file(MFILE *memfile, char *fname)
{
    if (memfile->start)
        detach_file( memfile);
  
    openfile(memfile,fname);
  
    memfile->mstart = memfile->dptr;
    memfile->mlen = memfile->len;
}








