#include	<stdio.h>
#include	<stat.h>
#include	<tos.h>
#define	CASE	break;case

extern	int histinsert(const char *filename);
extern	int main(int argc,char **argv);

int
histinsert(filename)
const char *filename;
{
  FILE *fp;
  char *fm;
  char *fme;
  struct stat statbuf ;
  size_t totalsize;
  void	*memstart;

#ifdef	__TURBOC__
  /* this code is here to get register D4 saved, because stat()
     in the turbo-c-library does modify it without saving */
  int i1,i2,i3,i4;
  i1=1;
  i2=1;
  i3=1;
  i4=i1+i2+i3;
#endif	__TURBOC__

  if (fp = fopen(filename,"r")) {
    stat(filename,&statbuf);
    if ((totalsize = coreleft()) > statbuf.st_size) {
      if (memstart = fm = (char*) Malloc(totalsize)) {
	fme = fm+fread(fm,sizeof(char),statbuf.st_size,fp);
	*fme++ = '\0'; /* for files, ending in an unterminated line */
	while (fm < fme) {
	  if (*fm == '\n' || *fm == '\r') *(fm)='\016';
	  fm++;
	}
	Mshrink(0,memstart,(size_t)fme-(size_t)memstart);
	fclose(fp);
	csystem(memstart);
	return 0;
      } else {
	fclose(fp);
	return 2;
      }
    } else {
      fclose(fp);
      return 3;
    }
  } else {
    return 4;
  }
}

int
main(argc,argv)
int argc;
char **argv;
{
  if (argc > 1) {
    switch (histinsert(argv[1])) {
      CASE 2:
	fprintf(stderr,"couldn't allocate memory\n");
      CASE 3:
	fprintf(stderr,"not enough memory available\n");
      CASE 4:
	fprintf(stderr,"couldn't open file %s\n",argv[1]);
    }
  }
  return 0;
}
