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

#include "EspaceUS.h"
#include "TestAlloc.h"

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

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

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

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

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

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

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

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

