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

#include "EspaceS.h"
#include "TestAlloc.h"

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

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

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

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

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

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

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

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

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

