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

#include "EspaceI.h"
#include "TestAlloc.h"

EspaceI::EspaceI(int dx,int dy) {
  this->dx = dx;
  this->dy = dy;
  good = 1;
  p =(int **) calloc(dy,sizeof(int *));
  testAllocAndExit(p,"new EspaceI(int,int)");
  if ( !p ) {
    good = 0;
    return; }
  for ( int i = 0 ; i < dy ; i++ ) {
    p[i] =(int *) calloc(dx+1,sizeof(int));
    testAllocAndExit(p[i],"new EspaceI(int,int)",i);
    if ( !p[i] ) {
      printf("!!!!!! %d\n",i);
      good = 0;
      return; } }
}

EspaceI::EspaceI(EspaceI *dd) {
  dx = dd->dx ;
  dy = dd->dy ;
  good = 1;
  p =(int **) calloc(dy,sizeof(int *)) ;
  if ( !p ) {
    good = 0;
    return; }
  for ( int i = 0 ; i < dy ; i++ ) {
    p[i] =(int *) calloc(dx+1,sizeof(int)) ;
    if ( !p[i] ) {
      good = 0;
      return; }
    memcpy(p[i],dd->p[i],(dx+1)*sizeof(int)); }
}

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

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

void EspaceI::init(int v) {
  for ( int i = 0 ; i < dy ; i++ )
    for ( int j = 0 ; j < dx+1 ; j++ )
      p[i][j] = v;
}

int EspaceI::cherche(int x,int y) {
  return(p[y][x]) ;
}

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

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

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

