/*
Copyright (C) 1991, Marcus J. Ranum. All rights reserved.
*/
#include "config.h"
#define DEFAULT_COMPTABLE
#include "comp.h"
static char ctab[128][128];
void comp_init ()
{
int i;
int j;
for (i = 0; i < 128; i++)
for (j = 0; j < 128; j++)
ctab[i][j] = 0;
for (i = 0; i < 128; i++)
ctab[(int) ctok[i][0]][(int) ctok[i][1]] = i | 0x80;
}
int compress (FILE * fin, FILE * fout)
{
char c;
char nxt = -1;
while (1) {
if (nxt == -1)
c = getc (fin);
else
c = nxt;
nxt = getc (fin);
if (ferror (fin) || feof (fin)) {
if (c != -1)
putc (c, fout);
return (ferror (fin) == 0);
}
if (ctab[(int) c][(int) nxt]) {
if (fputc (ctab[(int) c][(int) nxt], fout) == EOF)
return (1);
nxt = -1;
} else {
if (fputc (c, fout) == EOF)
return (1);
}
}
}
int decompress (FILE * fin, FILE * fout)
{
char c;
while (1) {
c = getc (fin);
if (feof (fin) || ferror (fin))
return (ferror (fin) == 0);
if (c & 0x80) {
putc (ctok[c & 0x7f][0], fout);
putc (ctok[c & 0x7f][1], fout);
} else
putc (c, fout);
}
}
int main (int ac, char *av[])
{
comp_init ();
if (ac < 2)
exit (compress (stdin, stdout));
else
exit (decompress (stdin, stdout));
}