/**handle the symbal table**
 **The interface is:
 **look_up(char *name,STACK *s)
 **current_install(Symbol *,STACK *)
 **get_label()
 **/
#include  "symbtab.h"
#include <iostream.h>
#include "scanner.h"
#define EXTERN extern
#include "global.h"
void push(STACK *);
void pop(STACK *);
void current_install(Symbol *,STACK *);
void delete_node(Symbol *);
void print_stack(STACK *s);

void print_stack(STACK *s)
{
Symbol *sym;
int i;
for(i=s->current_index;i>=0;i--)
  {
  sym=s->S[i];
  while(sym!=(Symbol *)NULL)
  {
   cout<<sym->name<<endl;
   sym=sym->next;
   }
 }
}





void delete_node(Symbol *root)
{
Symbol  *temp ,*sss;
sss=root;
if(root==(Symbol *)NULL)
return;
else {
while(sss!=(Symbol *)NULL)
   {
   temp=sss->next;
   delete(sss);  
   sss=temp;
   }
   }
}

Symbol* lookup(char *name,Symbol *root)  
{
Symbol *sss=root;
for(;;)
{
if(sss==(Symbol *)NULL)
break;
if(strcasecmp(sss->name,name)==0)
return sss;
else sss=sss->next;
}

return sss;
}


Symbol * look_up(char *name, STACK *s)
{
Symbol *sym;
int i;
leveldiff=0;
for(i=0;i<=s->current_index;i++)
  {
  sym=lookup(name,s->S[s->current_index-i]);
  if(sym!=(Symbol *)NULL)
  return sym;
  leveldiff++;
  }
return sym;
}

Symbol *install(Symbol *sym,Symbol *root)
{
Symbol *sss,*temp;
sss=root;
if(root==(Symbol *)NULL)
;
else {
while(sss!=(Symbol *)NULL)
   {
   temp=sss->next;
   if(!strcasecmp(sym->name,sss->name))
      {
      cout<<"Error:Id redefined at Line:"<<Line_Num<<endl;
      return root;
      }  
   sss=temp;
   }
   }
sym->next=root;
root=sym;
return root;
}

void current_install(Symbol *sym,STACK *s)
{
s->S[s->current_index]=install(sym,s->S[s->current_index]);
}


//it is a little different from the normal pop and push
void pop(STACK *s)
{
s->current_index--;
delete_node(s->S[s->current_index+1]);

}

void push(STACK *s)
{
s->current_index++;
s->S[s->current_index]=(Symbol *)NULL;
offset=5;
}

int get_label()
{
int i=globallabel;
globallabel++;
return i;
}
