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

#include "Espace.h"
#include "TestAlloc.h"

Espace::Espace(int dx,int dy,int nb) {
  this->dx = dx;
  this->dy = dy;
  this->nb = nb;
  p =(void ***) calloc(dy,sizeof(void **));
  testAllocAndExit(p,"new Espace(int,int,int)");
  if ( p ) {
    for ( int i = 0 ; i < dy ; i++ ) {
      p[i] =(void **) calloc(dx,nb);
      testAllocAndExit(p[i],"new Espace(int,int,int)",i); } }
}

Espace::Espace(Espace *dd) {
  dx = dd->dx ;
  dy = dd->dy ;
  nb = dd->nb ;
  p =(void ***) calloc(dy,sizeof(void **)) ;
  testAllocAndExit(p,"new Espace(Espace *)");
  if ( p ) {
    for ( int i = 0 ; i < dy ; i++ ) {
      p[i] =(void **) calloc(dx,nb) ;
      testAllocAndExit(p[i],"new Espace(Espace *)",i);
      if ( p[i] ) {
        memcpy(p[i],dd->p[i],dx*nb); } } }
}

Espace::~Espace(void) {
  for ( int i = 0 ; i < dy ; i++ )
    free(p[i]) ;
  free(p) ;
}

void Espace::init(unsigned char v) {
  for ( int i = 0 ; i < dy ; i++ )
    memset(p[i],(int) v,dx*nb) ;
}

void *Espace::cherche(int x,int y) {
  return(&p[y][x*nb]) ;
}

void Espace::sauve(void *c,int x,int y) {
  memcpy(&p[y][x*nb],c,nb) ;
}

long Espace::getUsedMemory(void) {
  long cpt = sizeof(Espace);
  cpt += dy*dx*nb ;
  cpt += dy*sizeof(void **) ;
  return(cpt);
}

int Espace::getUsedHandles(void) {
  int cpt = 1;
  cpt += dy ;
  cpt++ ;
  return(cpt);
}

