/*
 *	verbatim.c
 */

#include <stdio.h>
#ifdef __STDC__
#  include <stdlib.h>
#  include <string.h>
#else
#  include <strings.h>
#endif
#include <ctype.h>
 
#include "texchars.h"
#include "texchk.h"
 
extern int Verbose_Mode;

 
   void
do_verbatim (keyword)
   char *keyword;
{
  if (0 == strcmp("verbatim",keyword))
     find_end_verbatim("\\end{verbatim}");
  else if (0 == strcmp("verbatim*",keyword))
     find_end_verbatim("\\end{verbatim*}");
  else {
     fprintf(stderr,"Fatal error, bad argument to do_verbatim: %s\n",keyword);
     exit(1);
  }
  if (Verbose_Mode) {
     do_indent(--Indent_Level);
     printf("line %ld: \\end{%s}\n",(long)Current_Line,keyword); /*em*/
  }
}
 
 
/* get the next character after the 'verb' or 'verb*' command, then read */
/* until we find that character again. */
 
   void
do_verb ()
{
  int ch;
  int ch1;	/* (br) */

  ch = get_a_char();
  if (ch == EOF) {
     eof_verbatim_error();
     exit(1);
  }
  else if (isalpha(ch) || ch == '*' || ch == ' ' || ch == '\n') {
     verb_error((char)ch);  /*em*/
     exit(1);
  }
#if 0		/* mit Kanonen auf Spatzen geschossen ;-) (br) */
{
  char endchar[2];
  endchar[0] = (char)ch;    /*em*/
  endchar[1] = '\0';
  find_end_verbatim(endchar);
}
#else
  while( (ch1 = get_a_char()) != EOF ) {
     if( ch == ch1 )
	return;
  }
  eof_verbatim_error();
  exit(1);
#endif
}
 
 
/* Read characters until the exact characters constituting matchstring show */
/* up in the input stream, then return.  Matchstring may not contain '\n' */
 
   int
find_end_verbatim (matchstring)
   char *matchstring;
{
  static char Verbatim_Buffer[MAXLL];
  char *vbptr;
  int j,ch;
  int matchlen;
 
  matchlen = strlen(matchstring);
 
  /* matches cannot span lines, since matchstring cannot contain '\n' */
 
newline:
 
  for (j = 0; j < MAXLL; j++) Verbatim_Buffer[j] = '\0';
  vbptr = Verbatim_Buffer;
 
  /* Nothing can possibly match until we have read in as many characters as */
  /* there are in matchstring, so read that many in. */
 
  for (j = 0; j < matchlen; j++) {
      switch (ch = get_a_char()) {
        case '\n' :
          goto newline;
          break;
        case EOF :
          eof_verbatim_error();
          exit(1);
          break;
        default :
          Verbatim_Buffer[j] = (char)ch;    /*em*/
          break;
      }
  }
 
  /* check for a match, then read in the next character.  Keep checking */
  /* for a match against the last 'matchlen' characters. */
 
  j = matchlen;
  while (1) {
    if (0 == strcmp(matchstring,vbptr)) {
       return(1);
    }
    switch (ch = get_a_char()) {
      case '\n' :
        goto newline;
        break;
      case EOF :
        eof_verbatim_error();
        exit(1);
        break;
      default :
        Verbatim_Buffer[j] = (char)ch;  /*em*/
        break;
    }
    j++;
    vbptr++;
  }
}
