//
// Copyright(C) Simon Howard
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
//
// Escape text to HTML.
//

#include <stdio.h>
#include <stdlib.h>


typedef struct
{
  char c;              // character to detect
  char *replace;       // sequence to replace with
} replace_t;

// the replacements we want to make

static replace_t replace_chars[] =
  {
    {'<',   "&lt;"},
    {'>',   "&gt;"},
    {'&',   "&amp;"},
    {'\n',  "<br>\n"},
    {'\t',  "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"},
    {' ',   "&nbsp;"},
  };

static const int num_replace_chars =
 sizeof(replace_chars) / sizeof(*replace_chars);

// this is a table of replacements we keep for speed

static replace_t *replace_table[256];

static void build_replace_table()
{
  int i;

  // clear first

  for(i=0; i<256; i++)
    replace_table[i] = NULL;

  // fill in

  for(i=0; i<num_replace_chars; i++)
    replace_table[(int) replace_chars[i].c] = &replace_chars[i];
}

static void htmlise_stream(FILE *instream)
{
  printf("<tt>\n");

  while(!feof(instream))
    {
      int c = fgetc(instream);

      if(c < 0 || c >= 256)
        continue;

      if(replace_table[c])
	printf(replace_table[c]->replace);
      else
	putchar(c);
    }
  printf("</tt>\n");
}

int main(int argc, char *argv[])
{
  build_replace_table();

  if(argc < 2)
    htmlise_stream(stdin);
  else
    {
      FILE *fstream;

      fstream = fopen(argv[1], "r");

      htmlise_stream(fstream);

      fclose(fstream);
    }

}

