/* wf.c
   L. Stewart October 12, 1982  10:51 AM
   November 8, 1982  5:12 PM, added WriteProc
   March 10, 1983  2:59 PM, removed WriteProc
 */

#include <Env.h>

extern PutChar();
extern Block();
extern IsDigit();
extern Ugt();
extern UDiv();
extern URem();

wf(fmt)
  char *fmt;
  {
  while (*fmt != 0) PutChar(*fmt++);
  };

wfcr()
  {
  wf("\r");
  };

wf1(fmt, a1)
  char *fmt;
  int a1;
  {
  pfary(fmt, &a1);
  };

wf2(fmt, a1, a2)
  char *fmt;
  int a1, a2;
  {
  int ary[2];
  ary[0] = a1;
  ary[1] = a2;
  pfary(fmt, ary);
  };

wf3(fmt, a1, a2, a3)
  char *fmt;
  int a1, a2, a3;
  {
  int ary[3];
  ary[0] = a1;
  ary[1] = a2;
  ary[2] = a3;
  pfary(fmt, ary);
  };

wf4(fmt, a1, a2, a3, a4)
  char *fmt;
  int a1, a2, a3, a4;
  {
  int ary[4];
  ary[0] = a1;
  ary[1] = a2;
  ary[2] = a3;
  ary[3] = a4;
  pfary(fmt, ary);
  };

static pfary(fmt, ary)
  char *fmt;
  int *ary;
  {
  char c;
  while ((c = *fmt++) != 0) {
    Block();
    if (c == '%') fmt = doone(fmt, *ary++);
    else PutChar(c);
    };
  };

static char *doone(fmt, a1)
  char *fmt;
  int a1;
  {
  char c, fillchar, *last;
  char buf[20];
  int width, radix, i;
  fillchar = ' ';
  buf[0] = 0;
  width = 0;
  if (*fmt == '0') fillchar = '0';
  while ((c = *fmt++) != 0) {
    if (IsDigit(c)) width = (width * 10) + (c - '0');
    else break;
    };
  if (c == 'r') { ssw(a1); return(fmt); };
  if (c == 's') { wf(a1); return(fmt); };
  if (c == 'c') { PutChar(a1); return(fmt); };
  if (c == 'd') radix = -10;
  if (c == 'u') radix = 10;
  if (c == 'x') radix = 16;
  if (c == 'o') radix = 8;
  if (radix==0) return(fmt);
  last = putfnum(buf, a1, radix);
  if (width>0) {
    width -= (last-buf);
    while (width > 0) {
      Block();
      PutChar(fillchar);
      width -= 1;
      };
    };
  wf(buf);
  return(fmt);
  };

static ssw(s)
  struct ShortSTRING *s;
  {
  int i;
  for (i = 0; i < s->length; i += 1) PutChar(s->text[i]);
  };

static char *putfnum(buf, a1, radix)
  char *buf;
  int a1, radix;
  {
  int digit;
  if (radix<0) {
    radix = -radix;
    if (a1<0) {
      a1 = -a1;
      *buf++ = '-';
      };
    };
  if (!Ugt(radix, a1)) buf = putfnum(buf, UDiv(a1, radix), radix);
  digit = URem(a1, radix);
  if (digit>9) *buf++ = digit + 'A'-10;
  else *buf++ = digit + '0';
  *buf = 0;
  return(buf);
  };