
#include "yodl.h"

static int 
newlines (char const *s)	/* count newlines in string */
{
  int
    res = 0;

  while (*s)
    {
      if (*s == '\n')
	res++;
      s++;
    }
  return (res);
}

void 
parse ()
{
  char
   *total_lexbuf;

  last_written_char = 0;	/* assume no char written */

  lexer ();			/* prepare next token */

  while (1)			/* parse all files */
    {
      switch (lextok)
	{
	case tok_eof:		/* EOF, do next pass */
	  message (4, "<eof>\n");
	  return;

	case tok_space:	/* white space */
	  message (4, "<space>\n");
	  output_string (lexbuf);
	  lexer ();
	  break;

	case tok_string:	/* any string */
	  message (4, "<string> %s\n", lexbuf);
	  output_string (lexbuf);
	  lexer ();
	  break;

	case tok_anychar:	/* any character */
	  message (4, "<char> %s\n",
		   isprint (*lexbuf) ? lexbuf : "??");
	  output_string (lexbuf);
	  lexer ();
	  break;

	case tok_openpar:	/* open parenthesis */
	  message (4, "<openpar>\n");
	  output_string (lexbuf);
	  lexer ();
	  break;

	case tok_closepar:	/* close parenthesis */
	  message (4, "<closepar>\n");
	  output_string (lexbuf);
	  lexer ();
	  break;

	case tok_newline:	/* newline or paragraph */
	  message (4, "<newline-or-paragraph>\n");
	  total_lexbuf = xstrdup (lexbuf);
	  while (lextok == tok_space || lextok == tok_newline)
	    {
	      lexer ();
	      if (lextok == tok_space || lextok == tok_newline)
		total_lexbuf = str_concat (total_lexbuf, lexbuf);
	    }

	  if (newlines (total_lexbuf) > 1)
	    gram_PARAGRAPH (total_lexbuf);
	  else
	    output_string (total_lexbuf);

	  free (total_lexbuf);
	  break;

	case tok_symbol:	/* handle macro */
	  message (4, "<symbol> %s\n", lexbuf);
	  gram_symbol ();
	  break;
	}
    }
}
