/* HTML-ENCODE.C - MAIN PROGRAM FOR COMPRESSING HTML FILES. */

#include <stdio.h>
#include "code.h"
#include "freq.h"
#include "html.h"

main 
( int argc,
  char **argv
)
{   
  html_options options;		/* Options specifying how compression is done */
  html_context context;		/* Information on the current context */
  frequencies *freq;		/* Frequencies for current context */

  int ch; 			/* Next character to encode */
  int index;			/* Index of character to encode */

  /* Process command line options, exiting if there's an error. */

  if (html_arguments(&argv,&options)!=0 || *argv!=0)
  { fprintf (stderr,
     "Usage: html-encode [ -h | -H ] [ -p ] [ stats-file ] <HTML-file >encoded-file\n");
    exit(1);
  }

  /* Initialize arithmetic encoding modules. */

  start_outputing_bits();
  start_encoding();

  /* Initialize the context. */

  html_initial_context(&options,&context);

  /* Encode each character in turn, switching contexts as necessary. */

  for (;;)
  { 
    /* Read the next character to encode; terminate loop on EOF. */

    ch = getc(stdin);
    if (ch==EOF) break;

    /* Encode the character read using the current frequency table. */

    freq = html_find_table(&options,&context);
    index = freq->symbol_to_index[ch];
    encode_symbol(index,freq->cum_freq);

    /* Update frequencies for current context based on the character read. */

    update_frequencies(freq,index);

    /* Move to the new context, based on the character read. */

    html_next_context(ch,&options,&context);
  }

  /* Encode the EOF symbol. */

  freq = html_find_table(&options,&context);
  index = freq->symbol_to_index[EOF_symbol];
  encode_symbol(index,freq->cum_freq);

  /* Make sure the last bits get written out, then exit. */

  done_encoding();
  done_outputing_bits();

  exit(0);
}

