/*
 * Simple PASCAL compiler
 * File name: procedure.c 
 * ----------------------
 * This implements the procedure part. 
 *    Chakma Junan
 *    e993178@edu.tut.ac.jp
 *    Information and Computer Science
 *    Toyohashi University of Technology
 *
 * It was originally implemented by 
 *    ohno@edu.tut.ac.jp
 */
#include <stdio.h>
#include <stdarg.h>
#include "getsym.h"

#define	DEBUG	1

extern	TOKEN	tok;	
extern	FILE	*infile;
extern	FILE	*outfile;
extern	struct	list	*procedure_table;
extern	int	procedure_flag;

extern	void	statement();
extern	struct	list	*init_table();
extern	int	table(char *, struct list *);

void procedure();
void inblock();

void procedure()
{
    procedure_flag = 1; /* Initializing procedure flag */

    if(tok.attr == RWORD && tok.value == PROCEDURE) 
    {
       getsym();
       if(tok.attr == IDENTIFIER) 
       {
	  fprintf(outfile, "%s: \n", tok.charvalue);
	  getsym();
	  inblock();
	  if(tok.attr == SYMBOL && tok.value == SEMICOLON)
	  {
	     fprintf(outfile, "\n      return \n\n");
	     fprintf(stderr, "Procedure completed! \n");
	  } else error("line: %d: ';' required. ", tok.sline);
       } else error("line: %d: Procedure identifier is needed. ", tok.sline);
    } else error("line: %d: Procedure declaration in required.", tok.sline);
}

/*
 * Function: inblock
 * Usage: (void) inblock();
 * ------------------------
 * This function implements the inblock. 
 */
void inblock()
{
   procedure_table = init_table();

   if(tok.attr == SYMBOL && tok.value == LPAREN)
   {
      do
      {
	getsym();
	if(tok.attr == IDENTIFIER)
	{
	   table(tok.charvalue, procedure_table);
	}
      }while(tok.value != RPAREN);
   } else error("line: %d: '(' required. ", tok.sline);

   getsym();
   if(tok.value != SEMICOLON)
      error("line: %d: ';' required. ", tok.sline);

   getsym();
   if(tok.attr == RWORD && tok.value == VAR)
   {
       do
       {
	  getsym();
	  if(tok.attr == IDENTIFIER)
	  {
	     table(tok.charvalue, procedure_table);
	  }
       } while(tok.value != SEMICOLON);
   } else error("line: %d: A 'var' declaration is required.", tok.sline);
   getsym();
   statement();
}
