/*
 * Copyright (c) 1993 Niklas Rjemo
 * All rights reserved.
 * 
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose, without fee, and without written agreement is
 * hereby granted, provided that the above copyright notice and the following
 * two paragraphs appear in all copies of this software.
 * 
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE AUTHOR
 * HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE AUTHOR HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */

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

#include "extra.h"
#include "video.h"

static int totalmem = 0;

typedef struct MEM {
   struct MEM *prev;
   int    this;
} mem;

mem *allMem = 0;

void *Malloc(int x,char *file,int line)
{
  mem *p = malloc(x);
  if(p == NULL) {
    static char message[80];
    sprintf(message,"Not enough memory\nallocated %d\n want %d more",totalmem,x);
    werr(TRUE,message);
    return 0;
  } else {
    totalmem += x;
    fprintf(stderr,"%08x Allocated %6d bytes total %6d (%12s:%3d)\n",
                        (unsigned int)p,x,totalmem,file,line);
  }
  fflush(stderr);
  return p;
}

void *Realloc(void *p, int x,char *file,int line)
{
  mem *np = realloc(p,x);
  if(np == NULL) {
    static char message[80];
    sprintf(message,"Not enough memory\nallocated %d\n reallocate %d more",totalmem,x);
    werr(TRUE,message);
    return 0;
  } else {
    totalmem += x;
    fprintf(stderr,"%08x Reallocated to\n",(unsigned int)p);
    fprintf(stderr,"%08x new size %6d bytes total %6d (%12s:%3d)\n",
           (unsigned int)np,x,totalmem,file,line);
  }
  fflush(stderr);
  return np;
}

void Free(void **del,char *file,int line)
{
  fprintf(stderr,"%08x Free (%12s:%3d)",(unsigned int)*del,file,line);
  fflush(stderr);
  if(*del) {
    free(*del);
    *del = 0;
  }
  fprintf(stderr,"!\n");
}
 
long random()
{
  return rand();
}

unsigned int htonl(unsigned int i)
{
#if 1
  union {
    int i;
    struct {
     char a,b,c,d;
    } b;
  } fr,to;
  fr.i = i;
  to.b.a = fr.b.d;
  to.b.b = fr.b.c;
  to.b.c = fr.b.b;
  to.b.d = fr.b.a;
  return to.i;
#else
  return i;
#endif
}

int bzero(char *b, int length)
{
  memset(b,0,length);
  return 0;
}
