/*
 * This program performs the function of the PostScript Level 2 ASCII85Encode
 * filter. Use it to encode binary files for embedding into PostScript Level 2
 * programs where they'll be read with the ASCII85Decode filter.
 *
 * Based on btoa version 4.0 by Paul Rutter Joe Orost, modified for the present
 * purpose by Michael Sokolov.
 */

#include <stdio.h>

#define reg register

#define MAXPERLINE 78

int ccount = 0;
int bcount = 0;
long word;
int partiallast;

#define EN(c)	(int) ((c) + '!')

encode(c) reg c;
{
  word <<= 8;
  word |= c;
  if (bcount == 3) {
    wordout(word);
    bcount = 0;
  } 
  else {
    bcount += 1;
  }
}

wordout(word) reg long int word;
{
  if (word == 0 && !partiallast) {
    charout('z');
  } 
  else {
    reg int tmp = 0;

    if (word < 0)
    { /* Because some don't support unsigned long */
      tmp = 32;
      word = word - (long)(85L * 85 * 85 * 85 * 32);
    }
    if (word < 0) {
      tmp = 64;
      word = word - (long)(85L * 85 * 85 * 85 * 32);
    }
    charout(EN((word / (long)(85L * 85 * 85 * 85)) + tmp));
    word %= (long)(85L * 85 * 85 * 85);
    charout(EN(word / (85L * 85 * 85)));
    if (partiallast == 1)
	return;
    word %= (85L * 85 * 85);
    charout(EN(word / (85L * 85)));
    if (partiallast == 2)
	return;
    word %= (85L * 85);
    charout(EN(word / 85));
    if (partiallast == 3)
	return;
    word %= 85;
    charout(EN(word));
  }
}

charout(c) {
  putchar(c);
  ccount += 1;
  if (ccount == MAXPERLINE) {
    putchar('\n');
    ccount = 0;
  }
}

main(argc,argv)
char **argv;
{
  reg c;

  if (argc != 1) {
    fprintf(stderr,"bad args to %s\n", argv[0]);
    exit(2);
  }
  while ((c = getchar()) != EOF)
    encode(c);
  partiallast = bcount;
  while (bcount != 0) {
    encode(0);
  }
  putchar('~');
  putchar('>');
  putchar('\n');
  exit(0);
}
