#include "fsm.h"
#include "converter.h"
/**************************************************************************
Function: relabel()
Comments: This function replaces the "*" or the internal transitions in
	  the converter.data file..which is the resultant converter FSM
	  by the original internal transition.
Input:	  fsm_orig - original state machine
	  fsm_pr - the state machine which was labelled as a result of a
	  call to LabelEvents().
	  fsm_res - the state machine as a result of relabel.
Author:   Sudhir Nelvagal
Advisor:  Dr. Ratnesh Kumar
***************************************************************************/
void RelabelEvents(FSM *fsm_orig, FSM *fsm_pr, FSM *fsm_res)
{
	ST_LIST *current, *orig_ptr;
	TR_LIST *curr_trans, *orig_trans;
	int num_tran, orig_num_tran; 
	FILE *fp_out;

	if(!fsm_orig)
		prog_abort("RelabelEvents: Null pointer arg for FSM *");
	if(!fsm_pr)
		prog_abort("RelabelEvents: Null pointer arg for FSM *");
	if(!fsm_res)
		prog_abort("RelabelEvents: Null pointer arg for FSM *");

	fp_out = fopen("tmp", "w+");

	orig_ptr = fsm_orig->states; /* state ptr to the orig FSM */
	current = fsm_pr->states;  /* state ptr to the preconv FSM */
	fprintf(fp_out, "%d\n", get_NStates(fsm_pr));
	while(current) {
	orig_ptr = fsm_orig->states; /* state ptr to the orig FSM */
	while(orig_ptr)  {
	  /* If the state names in the converter and safetycheck output
	   match */
	   if(strcmp(current->name, orig_ptr->name)==0) {
		curr_trans = current->trans;
		num_tran = get_NTrans(current);
		orig_num_tran = get_NTrans(orig_ptr);
		fprintf(fp_out, "\n%s\t%d\t%d\n", current->name,
			current->marked, num_tran);
		orig_trans = orig_ptr->trans;

/* Important to have the original list in outer loop and current list in
   inner loop to eliminate writing duplicates.  This is inelegant but saves
   making changes to the library for this  */
		while(orig_trans) {
		   curr_trans = current->trans;
		   while(curr_trans) {
/* changed strcmp to strstr */
			if(strstr(curr_trans->next_state->name, 
			orig_trans->next_state->name)!=NULL) {
			    fprintf(fp_out,"%s\t%s\n",orig_trans->input, 
					curr_trans->next_state->name);
			    strcpy(curr_trans->input, orig_trans->input);
			    break;
			}
			curr_trans= curr_trans->next;
		   }/*while curr_trans ends */
		   orig_trans = orig_trans->next;	
		} /*while orig_trans ends */
	    } /* if strcmp ends */		
	    orig_ptr = orig_ptr->next;
	  } /* while orig_ptr ends */
	  fflush(fp_out);
	  current = current->next;
	} /* while current ends */
	fclose(fp_out);
	fsm_copy(fsm_pr, fsm_res);
#ifdef X
Thereis some problem when an fsm_read is done..correct this in final version */
	/* read it back into the fsm_res structure */
	fp_out = fopen("tmp", "r");
	fsm_read(fp_out, fsm_res);
	fclose(fp_out);
#endif
	unlink("tmp"); /* delete the file */
}	/* EOF*/
