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

#include "EspaceUI.h"
#include "TestAlloc.h"

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

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

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

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

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

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

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

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

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

