/* make_main.c
 */

#include <stdio.h>
#include <define.h>
#include <capldata.h>
#include <make_main.h>

extern FILE *main_fp;

static char main_proc_list[] = {"
#include <stdio.h>
#include <event.h>
#include <comm.h>
#include <SMessage.h>
#include <Henv.h>
#include <AgentFlags.h>

#include <CaplDef.h>
#include <CQueue.h>
#include <agent_info.h>
#include <world_info.h>

char *LOGICAL_AGENT_NAME = \"%s\";
char *PHYSICAL_AGENT_ID = \"%s\";
char *SUBSTANCE_PATH = %s;
char *SUBSTANCE = \"%s\";

int lock_swt = %d;
int
  main(int argc, char *argv)
{
  InitializeAgentProcess(argc, argv);
  AgentProcessMainLoop();
  TerminateAgentProcess();
  exit(0);
}

int InitializeAgentProcess(int argc, char *argv[])
{
  int fd;

  if (argc != 2){
    fprintf(stderr, \"usage : %%s port-number\\n\", argv[0]);
    exit(1);
  }
    
  agent_name = rindex (argv[0], \'/\');
  if (agent_name == NULL)  agent_name = argv[0];
  else                     agent_name++;
    
  if (init_comm(atoi(argv[1]), 0) < 0) exit (1);
  init_environment(argc, argv);
  if ((dFd = init_%s_substance(LOGICAL_AGENT_ID, SUBSTANCE_NAME)) < 0){
    fprintf(stderr, \"cannot connect to substance.\\n\");
    exit(1);
  }
  signal(SIGQUIT, agentCatchupSigQuit);
  AIInit(LOGICAL_AGENT_NAME, LOGICAL_AGENT_ID, fd);

}

int TerminateAgentProcess(void){
  close_environment();
  exit_application();
  close_simple_agent();
}

int SimpleAgentMainLoop(void)
{
  SMessage smg;
  int      eventType;
  int      eventData;
  enum QueueType qType;

  CQInit(queue[MsgQ]);
  CQInit(queue[SubIQ]);
  CQInit(queue[NPQ]);

  WIPush(NORMAL, QUERY_WAIT, (char *)NULL);

  while(agentInfo.activity == ON){
    if((smg = CQDequeue(queue[MsgQ], CONTROL, NULL, NULL, NULL)) != NULL) {
      appHandleDebugFlag(smg);
      CSMDelete(smg);
    }
    SelectMessage(&qType, &smg);
    if(smg == NULL){
      eventType = select_event(&eventData);
      switch(eventType){
      case EVENT_EXIT:
	agentInfo.activity = OFF;
	break;
      case EVENT_MESSAGE_SEND_READY:
	flush_message();
	break;
      case EVENT_MESSAGE_RECEIVE_READY:
	while(receive_message(&smg) == 0)
	  CQEnqueue(queue[MsgQ], smg);
	break;
      case EVENT_IO_READY:
	if (event_data == agentInfo.subFd){
	  while(ReceiveFromSubstance(&smg) == 0)
	    CQEnqueue(queue[SubIQ], smg);
	}
	else{
	  fprintf(stderr, \"receive data from unkown I/O.\\n\");
	}
	break;
      }
    }
    else{
      MethodProcedure(qType, smg);
    }
  }
  return 0;
}
/* end of CMain.c */
"
};

int make_main_file(void)
{
  fprintf(main_fp, main_proc_list,
	  agent_name, agent_id, path, inside_sub,
	  lock_swt, insides[0]);
  return TRUE;
}

/* end of make_main.c */
