/* Copyright (c) 2002 Speech and Acoustics Processing Lab., NAIST */
/*   All rights reserved   */
/*
 * jcontrol --- sample client for Julius server mode
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

#include "japi.h"

#define strmatch !strcmp

/* message buffer */
static char sbuf[MAXLINELEN];
static char rbuf[MAXLINELEN];

/* process each user command from stdin */
void
do_command(int sd)
{
  int n;
  char *p, *com, *arg1, *arg2;

  if (fgets(sbuf, MAXLINELEN, stdin) != NULL) {
    com = strtok(sbuf, " \t\n");
    arg1 = arg2 = NULL;
    if ((p = strtok(NULL, " \t\n")) != NULL) {
      arg1 = p;
      if ((p = strtok(NULL, " \t\n")) != NULL) {
	arg2 = p;
      }
    }
    if (strmatch(com, "die")) {
      japi_die(sd);
    } else if (strmatch(com, "version")) {
      japi_get_version(sd);
    } else if (strmatch(com, "status")) {
      japi_get_status(sd);
    } else if (strmatch(com, "pause")) {
      japi_pause_recog(sd);
    } else if (strmatch(com, "terminate")) {
      japi_terminate_recog(sd);
    } else if (strmatch(com, "resume")) {
      japi_resume_recog(sd);
    } else if (strmatch(com, "inputparam")) {
      japi_set_input_handler_on_change(sd, arg1);
    } else if (strmatch(com, "changegram")) {
      japi_change_grammar(sd, arg1);
    } else if (strmatch(com, "addgram")) {
      japi_add_grammar(sd, arg1);
    } else if (strmatch(com, "deletegram")) {
      japi_delete_grammar(sd, arg1);
    } else if (strmatch(com, "activategram")) {
      japi_activate_grammar(sd, arg1);
    } else if (strmatch(com, "deactivategram")) {
      japi_deactivate_grammar(sd, arg1);
    } else {
      fprintf(stderr,"No such command: [%s]\n", com);
    }
  }
}

/* output incoming data to stdout */
void
do_output(int sd)
{
  while(do_reveive(sd, rbuf, MAXLINELEN) != NULL) {
    if (rbuf[0] == '.' && rbuf[1] == '\0') break;
    printf("> %s\n", rbuf);
  }
}

/* handle input event */
void
command_loop(int sd)
{
  fd_set readfds;
  int i, nfd;

  for(;;) {

    /* watch socket (fd = sd) and stdin (fd = 0) */
    FD_ZERO(&readfds);
    FD_SET(sd, &readfds);
    FD_SET(0, &readfds);

    nfd = select(sd+1, &readfds, NULL, NULL, NULL);

    if (nfd < 0) {
      perror("Error: select");
      exit(1);
    }
    if (FD_ISSET(0, &readfds)) {
      /* stdin */
      do_command(sd);
    }
    if (FD_ISSET(sd, &readfds)) {
      /* from server */
      do_output(sd);
    }
  }
}  

/* output usage */
void usage()
{
  printf("usage: jcontrol host [portnum (def=%d)]\n", DEFAULT_PORT);
}

/* main */
int
main(int argc, char *argv[])
{
  int port;
  int sd;
  
  if (argc < 2) {
    usage();
    return 1;
  }
  if (argc < 3) {
    port = DEFAULT_PORT;
  } else {
    port = atoi(argv[2]);
  }
  sd = do_connect(argv[1], port);
  command_loop(sd);
}

