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

/* strip.c --- strip zero segments from speech data */

/* $Id: strip.c,v 1.2 2002/09/11 22:01:50 ri Exp $ */

#include <sent/stddefs.h>
#include <sent/speech.h>

/* distinction function: sequence of 0 and -2^15 is invalid */
#define IS_INVALID_SAMPLE(A) ((A) == 0 || (A) == -32767)
/* length to detect as invalid */
#define WINDOWLEN 16		/* 1ms in 16kHz */

int				/* return length after stripping */
strip_zero(SP16 a[], int len)
{
  int src,dst;
  int bgn,mode,j;

  dst = 0;
  bgn = 0;
  mode = 0;

  for (src = 0; src < len; src++) {
    if (IS_INVALID_SAMPLE(a[src])) {
      if (mode == 0) {          /* first time */
        bgn = src;
        mode = 1;
      }
      /* skip */
    } else {
      if (mode == 1) {
        mode = 0;
        if ((src - bgn) < WINDOWLEN) {
          for(j=bgn;j<src;j++) {
            a[dst++] = a[j];
	  }
        } else {
          /* deleted (leave uncopied) */
	  /*j_printf("Warning: sample %d-%d is invalid, stripped\n", bgn, src-1);*/
        }
      }
      a[dst++] = a[src];
    }
  }
  /* end process */
  if (mode == 1) {
    mode = 0;
    if ((src - bgn) < WINDOWLEN) {
      /* restore */
      for(j=bgn;j<src;j++) {
        a[dst++] = a[j];
      }
    } else {
      /* deleted (leave uncopied) */
      /*j_printf("Warning: sample %d-%d is invalid, stripped\n", bgn, src-1);*/
    }
  }
  
  return(dst);
}

