/* Author: Ram Samudrala (me@ram.org)
 *
 * January 1, 1997; Copyright (c) 1997 by Ram Samudrala.
 */

#include "cgi_defines.h"
#include "cgi_display.h"
#include "cgi_common.h"
#include "cgi_error_handlers.h"

void pre2table(char line[], char delim_string[], char cell_begin[], char cell_end[]);

#define MAX_LINE_LENGTH 2000
#define SSI_INCLUDE "SSI"

int content_type_displayed = FALSE;

/******************************************************************/

int main(int argc, char *argv[])
{
  char delim_string[20], *lp, line[MAX_LINE_LENGTH];
  FILE *pre_fp;
  int ssi_include = FALSE;

  strcpy(delim_string, " ");
  switch(argc)
    {
    case 2:
      break;
    case 3: /* if two arguments check if one was telling us if this is an SSI include */
      if (strcmp(argv[2], SSI_INCLUDE) == 0)
	ssi_include = TRUE;
      else
	strcpy(delim_string, argv[2]);
      break;
    case 4: /* 3 arguments means the last was a request for an SSI */
      strcpy(delim_string, argv[2]);
      ssi_include = TRUE;
      break;
    default:
      sprintf(line, "Usage: %s filename [delim] [%s]", argv[0], SSI_INCLUDE);
      display_error(line);
      break;
    }
  
  if (!ssi_include)
    {
      sprintf(line, "Table version of %s", argv[1]);
      display_content_type(line);
    }

  open_file(&pre_fp, argv[1], "r", argv[0]);
  
  printf("<table border>\n");
  while (fgets(line, MAX_LINE_LENGTH, pre_fp))
    {
      if (line[0] == '#') 
	{
	  lp = &line[1];
	  pre2table(lp, delim_string, "<th>", "</th>");
	}
      else
	{
	  lp = &line[0];
	  pre2table(lp, delim_string, "<td>", "</td>"); 
	}
    }
  printf("</table>\n");
  close_file(&pre_fp, argv[1], argv[0]);
  return 1;
}

/******************************************************************/

void pre2table(char line[], char delim_string[], char cell_begin[], char cell_end[])
{
  char *buf;
  
  if ((buf = (char *) malloc(sizeof(char) * STRING_LENGTH)) == NULL)
    display_error("pre2table(): out of memory!");

  printf("<tr>\n");
  buf = strtok(line, delim_string);  
  while (buf != NULL)
    {
      if (buf[strlen(buf)-1] == '\n') 
	buf[strlen(buf)-1] = '\0';      
      printf("  %s %s %s\n", cell_begin, buf, cell_end);
      fflush(stdout);
      buf = strtok(NULL, delim_string);
    }  
  printf("</tr>\n");
  return;
}

/******************************************************************/
