#include <stdio.h>
#include <stdlib.h>

#include "FileLoader.h"
#include "FileUtils.h"

FileLoader::FileLoader(char *filename) {
  load(filename,20);
}

FileLoader::FileLoader(char *filename,int largeurTampon) {
  load(filename,largeurTampon);
}

char FileLoader::tc(size_t sn) {
  return(t[sn>>largeurTampon][sn&masque]);
}

int FileLoader::load(char *fileName,int llargeurTampon) {
  bufferSize = 1;
  bufferSize <<= llargeurTampon;
  this->largeurTampon = llargeurTampon;
  this->masque = bufferSize-1;
  t = NULL;
  size =(size_t) fileSize(fileName);
  printf("%lld\n",(long long) size);
  if ( size == -1 )
    return(0);
  n = (size+bufferSize-1)/bufferSize;
  t =(char **) calloc(n,sizeof(char *));
  for ( size_t i = 0 ; i < n ; i++ ) {
    size_t sz = size-i*bufferSize;
    if ( sz > bufferSize )
      sz = bufferSize;
    t[i] =(char *) calloc(sz,sizeof(char));
    if ( !t[i] )
      i = n; }
  if ( t[n-1] ) {
    size_t cpt = 0;
    FILE *f = fopen(fileName,"rb");
    for ( size_t i = 0 ; i < n ; i++ ) {
      printf("*");
      size_t sz = size-i*bufferSize;
      if ( sz > bufferSize )
        sz = bufferSize;
      cpt += sz;
      fread(t[i],1,sz,f); }
    fclose(f);
    printf(" %lld -\n",(long long) cpt);
    return(1); }
    else {
    if ( t ) {
      for ( size_t i = 0 ; i < n ; i++ )
        if ( t[i] )
          free(t[i]);
      free(t);
      t = NULL; }
    return(0); }
}

FileLoader::~FileLoader(void) {
  if ( t ) {
    for ( size_t i = 0 ; i < n ; i++ )
      if ( t[i] )
        free(t[i]);
    free(t);
    t = NULL; }
}

///
/// Retour de la quantite de memoire utilisee.
///
/// @return La quantite de memoire utilisee.
/// @author Nicolas Janey
/// @author nicolas.janey@univ-fcomte.fr
/// @version 1.0, 01/01/10
///
size_t FileLoader::getUsedMemory(void) {
  size_t mem = sizeof(FileLoader);
  if ( t ) {
    for ( size_t i = 0 ; i < n ; i++ )
      if ( t[i] ) {
        size_t sz = size-i*bufferSize;
        if ( sz > bufferSize )
          sz = bufferSize;
        mem += sz; }
    mem += n*sizeof(char *); }
  return(mem);
}

///
/// Retour du nombre de handles memoires utilises.
///
/// @return le nombre de handles memoires utilises.
/// @author Nicolas Janey
/// @author nicolas.janey@univ-fcomte.fr
/// @version 1.0, 01/01/10
///
long FileLoader::getUsedHandles(void) {
  long mem = 1;
  if ( t ) {
    for ( size_t i = 0 ; i < n ; i++ )
      if ( t[i] )
        mem++;
    mem++; }
  return(mem);
}
