/* Copyright (c) 1991-2002 Doshita Lab. Speech Group, Kyoto University */
/* Copyright (c) 2000-2002 Speech and Acoustics Processing Lab., NAIST */
/* Copyright (c) 2000-2002 IPA */
/*   All rights reserved   */

/* record.c --- record recognized speech input into successive file */

/* filenames are YYYY.MMDD.HHMMSS.raw */

#include <julius.h>
#include <time.h>

#define TSTRLEN 18

static char tstr[TSTRLEN];
static char recfilename[MAXLINELEN], finalfilename[MAXLINELEN];
static int fd;
static int totalnum;

/* make base filename string from current system time */
static void
timestring(char *t, int maxlen)
{
  time_t timep;
  struct tm *lmtm;

  time(&timep);
  lmtm = localtime(&timep);

  snprintf ( t, maxlen,"%04d.%02d%02d.%02d%02d%02d", 1900+lmtm->tm_year, 1+lmtm->tm_mon, lmtm->tm_mday, lmtm->tm_hour, lmtm->tm_min, lmtm->tm_sec);
}

/* make file pathname: [record_dirname]/[timestring()].raw */
static void
make_record_filename(char *buf, int buflen, char *filename)
{
  if (record_dirname == NULL) {
    j_error("no record directory specified??\n");
  }
  snprintf(buf, buflen, "%s/%s.raw", record_dirname, filename);
}

/* make temporary pathname: record_dirname/tmprecord.$(pid) */
static void
make_tmp_filename(char *buf, int buflen)
{
  snprintf(buf, buflen, "%s/tmprecord.%d", record_dirname, getpid());
}  

/* open temporary file for recording */
void
record_sample_open()
{
  make_tmp_filename(recfilename, MAXLINELEN);
  if ((fd = open(recfilename, O_CREAT|O_WRONLY|O_TRUNC, 0644)) < 0) {
    perror("Error: record_sample_open");
    j_error("failed to open \"%s\" (temporary record file)\n", recfilename);
  }

  totalnum = 0;
}

/* write samples to file */
void
record_sample_write(SP16 *speech, int samplenum)
{
  int cnt;

  cnt = wrsamp(fd, speech, samplenum);
  if (cnt < 0) {
    perror("Error: record_sample_write");
    j_error("failed to write samples to \"%s\"\n", recfilename);
  }
  cnt /= sizeof(SP16);		/* bytes -> samples */
  if (cnt < samplenum) {
    j_error("failed to write samples to \"%s\"\n", recfilename);
  }

  /* make timestamp of system time when an input begins */
  /* the current temporal recording file will be renamed to this time-stamp filename */
  if (totalnum == 0) {		/* beginning of recording */
    timestring(tstr, TSTRLEN);
  }
  
  totalnum += samplenum;
}

/* close the current file */
void
record_sample_close()
{
  if (close(fd) != 0) {
    perror("Error: record_sample_close");
  }

  /* now rename the temporary file to time-stamp filename */
  make_record_filename(finalfilename, MAXLINELEN, tstr);
  if (rename(recfilename, finalfilename) < 0) {
    perror("Error: record_sample_close");
    j_error("failed to move %s to %s\n", recfilename, finalfilename);
  }
  if (verbose_flag) {
    j_printerr("recorded to \"%s\" (%d bytes, %.2f sec.)\n", finalfilename, totalnum * sizeof(SP16), (float)totalnum / (float) smpFreq);
  }
}
