#include "fsm.h"
#include "converter.h"
int IN_CONTROL;
int INITIAL;
/*************************************************************************
Function: LabelEvents()
Comments: This function replaces all the internal transitions and marks
	  them as internal events or transitions.
Input:	  fsm_pr - this is the state machine which needs to be labelled
	  fp - file pointer to the event set which should NOT be labelled
	  differently from what it already is. i.e events not present in
	  the file are labelled as internal events.
NOTE:     VERY IMPORTANT----IN case there are different events which are
	  labelled as "*" and they happen to lead to the same state, then
	  using any library routines will result in an error as it will
	  detect them as duplicates and delete all but one of them.  So
	  use this routine with caution, and if possible don't use underlying
	  library calls like fsm_print and fsm_read until and after you have
	  relabelled all the transitions back to it its original labels.
Author:   Sudhir Nelvagal
Advisor:  Dr. Ratnesh Kumar
*****************************************************************************/
void LabelEvents(FSM *fsm_pr, FILE *fpr)
{
	char *buffer[MAX_LENGTH];
	int i=0,count=0,j=0, k=0,ext_hit=0, ext_miss=0, no_trans=0;
	int no_of_states=0;
	ST_LIST *current;
	TR_LIST *current_tr;
	
	if(!fsm_pr)
		prog_abort("LabelEvents: Null pointer passed as arg for FSM* ");
	if(!fpr)
		prog_abort("LabelEvents: Invalid file pointer");

	for(i=0;i<MAX_LENGTH;i++) { /*not best use of MAX_LENGTH*/
		buffer[i] = (char *)calloc(sizeof(char),LENGTH);
	}
	i=0;

	/* read the events from events.data into the buffer */
	while(fscanf(fpr, "%s", buffer[i++])==1) {
		;	
	}
	count = i-1;
	/* Initialize all the pointers to point ot the first state and tran */
	current = fsm_pr->states;
	current_tr = fsm_pr->states->trans;
	while(current) {
	   no_trans = get_NTrans(current);
	   while(no_trans) {	
		/* if (x,y) such that y !=dump */
		if(strstr(current->name, "dump")==NULL) {
			ext_hit=0; ext_miss=0;
			for(j=0;j<count;j++) {
				if(strcmp(current_tr->input,buffer[j])==0){
					ext_hit++; /*event was ext event */
				}
				else {
					ext_miss++; /* event was int event */
				}
			}
			if(ext_miss==count) {
			/* Then the event was an internal event */
				strcpy(current_tr->input, "*");
			}
		}	/* if strstr */
		current_tr = current_tr->next; /* Next transition */
		no_trans--;
	   } /* while no_trans */
	   current=current->next;	/* Next state */
	   /* reinitialize trans ptr to point to next state's transition
           as long as all the states are not covered */
	   if(current) {
		current_tr = current->trans;
	   } 
	} /*while current ends */


	for(i=0;i<MAX_LENGTH;i++) {
		free(buffer[i]);
	}
  } 
