/* code.c */
/* author: Edward A. Green */
/* purpose: code to generate and delete quads in memory, and to */
/*          give basic block assignments */

#include "proj3.h"

/*************************************************/
/* CODE ROUTINES */
/*****************/

/* add code to the current block */
void keep_code(BLOCK *blk, char *fld[5], int line_no)
{
	int i;
	CODE *code;
	char   *strsave(char *subject);


	if (blk==NULL)
	  {
	  printf("can\'t enter code to a NULL block\n");
	  exit(1);
	  }

	/* allocate space */
	if (NULL==(code=(CODE *)malloc(sizeof(CODE))))
	  {
	  printf("no more room on allocation of code\n");
	  exit(1);
	  }

	/* fill fields */
	code->basic=-1;
	code->line=line_no;
	for (i=0; i<5; i++)
	  code->flds[i]=strsave(fld[i]);
	code->used=NULL;
	code->mod=NULL;

	/* link into current code stream */
	if (blk->lead==NULL)
	  {
	  code->last=code;
	  code->next=code;
	  blk->lead=code;
	  }
	else
	  {
	  code->last=blk->lead->last;
	  code->next=blk->lead;
	  blk->lead->last->next=code;
	  blk->lead->last=code;
	  }

	return;
}


/* FILL IN THE CODE'S BASIC BLOCK FIELD GIVEN THE HEADER LINES. */
/*        GIVE THEM SERIAL NUMBERS. */
void add_basics(BLOCK *blocks, LEADS *leads)
{
	CODE *code;
	BLOCK *blk;
	int   blk_no;

	blk_no=0;
	blocks->last->next=NULL;
	leads=leads->next;

	for (blk=blocks; blk!=NULL; blk=blk->next)
	  {
	  blk->lead->last->next=NULL;
	  for (code=blk->lead; code!=NULL; code=code->next)
	    {
	    if (leads!=NULL)
	      if (code->line==leads->line)
		{
		blk_no++;
		leads=leads->next;
		}
	    code->basic=blk_no;
	    }
	  blk->lead->last->next=blk->lead;
	  }
	blocks->last->next=blocks;
	return;
}


/* REMOVE A QUAD FROM IT'S CODE LIST */
void dispose_code(CODE *code)
{
	int i;
	MOD *m;

	while (code->mod!=NULL)
	  {
	  m=code->mod;
	  code->mod=m->next;
	  if (m->var!=NULL) free(m->var);
	  free(m);
	  }

	while (code->used!=NULL)
	  {
	  m=code->used;
	  code->used=m->next;
	  if (m->var!=NULL) free(m->var);
	  free(m);
	  }

	for (i=0; i<5; i++)
	  if (code->flds[i]!=NULL) free(code->flds[i]);

	free(code);
	return;
}
