/* Copyright (c) 2002 Speech and Acoustics Processing Lab., NAIST */
/*   All rights reserved   */

#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include "japi.h"

static char buf[MAXLINELEN];	/* be careful: this buffer is shared among several functions for efficiency */

/* grammar file existing check */
static int
check_grammar_path(char *prefix)
{
  snprintf(buf, MAXLINELEN, "%s.dfa", prefix);
  if (access(buf, R_OK) < 0) {
    perror("japi_change_grammar"); return -1;
  }
  snprintf(buf, MAXLINELEN, "%s.dict", prefix);
  if (access(buf, R_OK) < 0) {
    perror("japi_change_grammar"); return -1;
  }
  return 0;
}

/* send grammar body */
static int
send_grammar(int sd, char *prefix)
{
  FILE *fp;
  
  snprintf(buf, MAXLINELEN, "%s.dfa", prefix);
  if ((fp = fopen(buf, "r")) == NULL) {
    perror("japi_change_grammar"); return -1;
  }
  while(fgets(buf, MAXLINELEN, fp) != NULL) {
    do_send(sd, buf);
  }
  do_send(sd, "DFAEND\n");
  fclose(fp);
  snprintf(buf, MAXLINELEN, "%s.dict", prefix);
  if ((fp = fopen(buf, "r")) == NULL) {
    perror("japi_change_grammar"); return -1;
  }
  while(fgets(buf, MAXLINELEN, fp) != NULL) {
    do_send(sd, buf);
  }
  do_send(sd, "DICEND\n");
  fclose(fp);
  return 0;
}

/* send comma-separated grammar ID list (ex. "1,3,5") */
static int
send_idlist(int sd, char *idstr)
{
  char *p;

  /* convert comma to space */
  strcpy(buf, idstr);
  p = buf;
  while(*p != '\0') {
    if (*p == ',') *p = ' ';
    p++;
  }
  /* send them */
  do_sendf(sd, "%s\n", buf);
  return 0;
}


void
japi_change_grammar(int sd, char *prefixpath)
{
  /* file existing check */
  if (check_grammar_path(prefixpath) < 0) return;
  /* send data */
  do_send(sd, "CHANGEGRAM\n");
  send_grammar(sd, prefixpath);
}

void
japi_add_grammar(int sd, char *prefixpath)
{
  /* file existing check */
  if (check_grammar_path(prefixpath) < 0) return;
  /* send data */
  do_send(sd, "ADDGRAM\n");
  send_grammar(sd, prefixpath);
}

void
japi_delete_grammar(int sd, char *idlist)
{
  do_send(sd, "DELGRAM\n");
  send_idlist(sd, idlist);
}

void
japi_activate_grammar(int sd, char *idlist)
{
  do_send(sd, "ACTIVATEGRAM\n");
  send_idlist(sd, idlist);
}

void
japi_deactivate_grammar(int sd, char *idlist)
{
  do_send(sd, "DEACTIVATEGRAM\n");
  send_idlist(sd, idlist);
}
