/*
 $Id: mzibutil.cc,v 1.3 1996/10/11 16:16:37 roitzsch Exp $
 (C)opyright 1996 by Konrad-Zuse-Center, Berlin
 All rights reserved.
 Part of the Kaskade distribution
*/

#include <stdio.h>

#include "mzibutil.h"


long allocMem = 0L;


char * ZIBAlloc(long size)
{
    char *buf;
    buf = (char*)malloc(size);
	if (buf!=nil) allocMem += size;
    memset(buf,NUL,size);
    return buf;
}

void ZIBFree(char *buf)
{
    free(buf);
	return;
}

int ZIBReadFile(const char* name, char** buffer)
{
    FILE *fd;
    long textLng;
    int rc;
    
    fd = fopen(name,"r");
    if (fd==nil)
    { 
	printf("File '%s' could not be opened\n", name);
	return False;
    }
    rc = fseek(fd, 0L, 2);
    if (rc!=0)
    {
	printf("fseek failed on %s\n",name);
	fclose(fd);
	*buffer = nil;
	return False;
    }
    textLng = ftell(fd);
    rewind(fd);
    *buffer = ZIBAlloc(textLng+10L);
    if (*buffer==nil)
    {
	printf("Not enough memory to store %ld bytes of '%s'\n",
	       textLng, name);
	fclose(fd);
	*buffer = nil;
	return False;
    }
    textLng = fread(*buffer,1L,textLng,fd);
    (*buffer)[textLng] = '\0';
    fclose(fd);
    
    return True;
}


int ZIBCreateFile(char *name)
  {
    FILE *output;
	output = fopen(name, "r");
	if (output!=nil)
	  {
	    printf("\tFile '%s' exists and will be overwritten\n", name);
	    fclose(output);
	  }
	else
	  {
	    output = fopen (name, "w"); /* should be Macs Create */
		if (output==nil) return False;
		fclose(output);
	  }
	return True;
  }

static FILE *outFile = stdout;
int ZIBPrintf(char* format,char* p1,char* p2,char* p3,char* p4)
  {
    int rc;

	if (outFile==nil) outFile = fopen("test.output","w");
	if (outFile==nil)
	  {
	    printf("Nothalt, 'test.output' already opened?\n");
	    exit(2);
	  }
	rc = fprintf(outFile,format,p1,p2,p3,p4);
	fflush(outFile);

	return rc;
  }

int ZIBStdOut(char *s)
  {
    return printf("%s",s);
  }

void ZIBNL()
  {
    putc('\n',outFile);
	return;
  }
