/*
 *     Routines which provide a single entry point to system routines,
 *     for easier debugging and porting.
 */

#include <stdio.h>
#include <ctype.h>
#include "make.h"
#define PTRSIZE 4

extern int errno;

/*
 *     The system calls malloc()/calloc() really return a pointer suitable
 *     for use to store any object (satisfies worst case alignment
 *     restrictions).  As such, it should really have been declared as
 *     anything BUT "char *".
 *
 *     Also, this gives us the opportunity to verify that the memory
 *     allocator really does align things properly.
 *
 *     Note that we choose to make calloc () the standard memory
 *     allocator, rather than malloc (), because it has a potentially
 *     bigger "bite" (total is product of two ints, rather than a
 *     single int).
 */

long *Calloc (nelem, elsize)
unsigned int nelem;
unsigned int elsize;
{
    extern char *calloc ();
    long *newmem;

#ifndef MCH_AMIGA
    long total;
#endif
    
    DBUG_ENTER ("malloc");
    DBUG_4 ("mem1", "allocate %u elements of %u bytes", nelem, elsize);
    DBUG_3 ("mem2", "total of %ul bytes", total = nelem * elsize);
    newmem = (long *) calloc (nelem, elsize);
    DBUG_3 ("mem", "allocated at %x", newmem);
    DBUG_RETURN (newmem);
}

#ifdef MCH_AMIGA

int system(cmd)
char *cmd;
{
    char **xrgs,*malloc(),*myrealloc();
    register char *ptr;
    register int i,j;
    int status = -1;
    
    DBUG_ENTER ("system");
   	ptr = cmd;
   	i = 0;
   	xrgs = (char **) malloc(PTRSIZE);
   	while (*ptr) {
   		while (isspace(*ptr)) {
   			if (*ptr == 0)
   				break;
   			ptr++;
   			}
		if (*ptr) {
			xrgs = (char **) myrealloc(xrgs,PTRSIZE * (i+2));
			if (xrgs == NULL) {
				puts("system: out of mem");
				exit(1);
				}
			xrgs[i++] = ptr;
			}
		while (*ptr)
			if (! isspace(*ptr))
				ptr++;
			else
				break;
		if (*ptr)
			*ptr++ = 0;
		}
	xrgs[i] = NULL;
	if ((fexecv(xrgs[0],xrgs)) != 0)
		DBUG_RETURN (errno);
	else
		DBUG_RETURN(wait());
}

char *myrealloc(ptr,nb)
char		*ptr;
unsigned	nb;
{
	char	*tptr,*malloc();

	tptr = malloc(nb);
	if (tptr != NULL) {
		movmem(ptr,tptr,nb);
		free(ptr);
		}
	return(tptr);
}
#endif /* MCH_AMIGA */
