#include <stdio.h>
#include "util.h"
#include "dev.h"

char *outfname, *infname, *user, *host, *pgmnam, efn[256];
FILE *ef;
int olderrfd,debugging;

/* Utility procedures
 */

open_ef()
{
  if (!debugging) {
    sprintf(efn,"/usr/tmp/%s.err.XXXXXX",pgmnam);
    if (!(ef = fopen(mktemp(efn),"w+"))) croak("couldn't open %s",efn);
    unlink(efn);
    fflush(stderr); olderrfd = dup(2); close(2); dup(fileno(ef));
  }
}

close_ef()
{
  long fpos;

  if (ef) {
    /* Now put back the old stderr */
    (void) fflush(stderr);
    fpos = ftell(stderr);
    close(2); dup(olderrfd); close(olderrfd);
    /* And print out anything that was sent to stderr */
    if (fpos > 0) {
      rewind(ef);
      dev_print_log(ef);
    }
    (void) fclose(ef);
    ef = NULL;
  }
}

/*VARARGS1*/
debug(fmt,a,b,c,d,e)
     char *fmt;
     long a,b,c,d,e;
{
    if (debugging) fprintf(stderr,fmt,a,b,c,d,e);
}

/*VARARGS1*/
croak(fmt,a,b,c,d,e)
     char *fmt;
     long a,b,c,d,e;
{
  fprintf(stderr,"%s: ",pgmnam);
  fprintf(stderr,fmt,a,b,c,d,e);
  fprintf(stderr,"\n");
  if (debugging) {
    perror("last error");
    if (infname) fprintf(stderr,"input file %s\n",infname);
    if (outfname) fprintf(stderr,"output file %s\n",outfname);
    if (user && host) fprintf(stderr,"running for %s@%s\n",user,host);
  }
  close_ef();
  exit(0);
}

swallow(nchars,f)
     long nchars;
     FILE *f;
{
  while (nchars-- > 0) (void) getc(f);
}

unsigned long get2(f)
     FILE *f;
{
  register unsigned long x;

  x = getc(f);
  x = (x << 8) | getc(f);
  return(x);
}

unsigned long get3(f)
     FILE *f;
{
  register unsigned long x;

  x = getc(f);
  x = (x << 8) | getc(f);
  x = (x << 8) | getc(f);
  return(x);
}

unsigned long get4(f)
     FILE *f;
{
  register unsigned long x;

  x = getc(f);
  x = (x << 8) | getc(f);
  x = (x << 8) | getc(f);
  x = (x << 8) | getc(f);
  return(x);
}

long sget2(f)
     FILE *f;
{
  register long x;

  x = ((long) ((char) getc(f)));
  x = (x << 8) | getc(f);
  return(x);
}

long sget3(f)
     FILE *f;
{
  register long x;

  x = ((long) ((char) getc(f)));
  x = (x << 8) | getc(f);
  x = (x << 8) | getc(f);
  return(x);
}

long sget4(f)
     FILE *f;
{
  register long x;

  x = ((long) ((char) getc(f)));
  x = (x << 8) | getc(f);
  x = (x << 8) | getc(f);
  x = (x << 8) | getc(f);
  return(x);
}

put4(l,f)
     unsigned long l;
     FILE *f;
{
  putc((l >> 24) & 0377,f);
  putc((l >> 16) & 0377,f);
  putc((l >> 8) & 0377,f);
  putc(l & 0377,f);
}

put2(s,f)
     unsigned short s;
     FILE *f;
{
  putc((s >> 8) & 0377,f);
  putc(s & 0377,f);
}