/*

  This is a part of the Project Frontier's Source code.

  Copyright (C) 1997-98 Francis Gastellu
                    aka Lone Runner/Aegis

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
#include <stdio.h>
#include <dos.h>

long coreleft(void)
{
unsigned par;
asm {
	mov ah, 0x48
    mov bx, 0xFFFF
    int 0x21
    mov par, bx
    }
return (long)par*16;
}

long farcoreleft(void)
{
unsigned par;
asm {
	mov ah, 0x48
    mov bx, 0xFFFF
    int 0x21
    mov par, bx
    }
return (long)par*16;
}

void *malloc(unsigned size)
{
unsigned par = (size+4)/16+1;
unsigned blk;
asm {
	mov ah, 0x48
    mov bx, par
    int 0x21
    jc error
    mov blk, ax
	}
(*(long*)MK_FP(blk, 0)) = size;
return (char *)MK_FP(blk, 4);
error:
return NULL;
}

void *farmalloc(long size)
{
unsigned par = (size+4)/16+1;
unsigned blk;
asm {
	mov ah, 0x48
    mov bx, par
    int 0x21
    jc error
    mov blk, ax
	}
(*(long*)MK_FP(blk, 0)) = size;
return (char *)MK_FP(blk, 4);
error:
return NULL;
}

void free(void *p)
{
unsigned segm = FP_SEG(p);
asm {
	mov ah, 0x49
    mov es, segm
    int 0x21
    }
}

void farfree(void *p)
{
unsigned segm = FP_SEG(p);
asm {
	mov ah, 0x49
    mov es, segm
    int 0x21
    }
}

void *realloc(void *p, unsigned size)
{
long s;
char *p2;
unsigned segm = FP_SEG(p);
unsigned par = (size+4)/16+1;
asm {
	mov ah, 0x4a
    mov bx, par
    mov es, segm
    int 0x21
    jc error
	}
(*(long*)MK_FP(segm, 0)) = size;
return p;
error:

s = (*(long*)MK_FP(segm, 0));
p2 = malloc(size);
if (p2 == NULL)
	{
    free(p);
    return NULL;
    }

memcpy(p2, p, s);
free(p);

return p2;
}

void *farrealloc(void *p, long size)
{
long s;
char *p2;
unsigned segm = FP_SEG(p);
unsigned par = (size+4)/16+1;
asm {
	mov ah, 0x4a
    mov bx, par
    mov es, segm
    int 0x21
    jc error
	}
(*(long*)MK_FP(segm, 0)) = size;
return p;
error:

s = (*(long*)MK_FP(segm, 0));
p2 = malloc(size);
if (p2 == NULL)
	{
    free(p);
    return NULL;
    }

memcpy(p2, p, s);
free(p);

return p2;
}

void *calloc(unsigned size, int n)
{
void *p;
p = malloc(size*n);
memset(p, 0, size*n);
return p;
}

