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

#include "EspaceP.h"
#include "TestAlloc.h"

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

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

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

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

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

void EspaceP::sauve(void *c,int x,int y) {
  p[y][x] = c ;
}

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

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

