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

/* zmean.c --- subtract zero mean from speech sample */

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

/* same as ZMEANSOURCE in HTK */

#include <sent/stddefs.h>

void
sub_zmean(SP16 *speech, int samplenum)
{
  int i;
  float d, sum, zmean;
  
  /* calc zmean */
  sum = 0.0;
  for (i=0;i<samplenum;i++) {
    sum += speech[i];
  }
  zmean = sum / (float)samplenum;

  for (i=0;i<samplenum;i++) {
    d = (float)speech[i] - zmean;
    /* clip overflow */
    if (d < -32768.0) d = -32768.0;
    if (d > 32767.0) d = 32767.0;
    /* round to SP16 (normally short) */
    if (d > 0) speech[i] = (SP16)(d + 0.5);
    else speech[i] = (SP16)(d - 0.5);
  }
}
