/* This is -*- C -*- */
/* vim: set sw=2: */
/* $Id$ */

/*
 * meter.c
 *
 * Copyright (C) 2003 The Free Software Foundation, Inc.
 *
 */

/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "meter.h"

Meter *
meter_from_phoneme_decomp (Phoneme *p)
{
  Meter *m;
  int i, count = 0;

  g_return_val_if_fail (p != NULL, NULL);

  for (i = 0; p[i]; ++i) {
    if (PHONEME_IS_EXPLICITLY_STRESSED (p[i]))
      count += 1;
  }
   
  m = g_new (Meter, count+1);
  m[count] = '\0';

  for (i = 0; p[i]; ++i) {
    if (PHONEME_IS_EXPLICITLY_STRESSED (p[i])) {
      --count;
      m[count] = PHONEME_IS_STRESSED (p[i]) ? 
	METER_STRESSED : METER_UNSTRESSED;
    }
  }

  return m;
}

double
metric_error_left (Meter *a, Meter *b)
{
  int i;
  double tally = 0;
  
  g_return_val_if_fail (a != NULL, 1000);
  g_return_val_if_fail (b != NULL, 2000);

  for (i = 0; a[i] && b[i]; ++i)
    tally += METER_ERROR (a[i], b[i]);

  return tally;
}

double
metric_error_right (Meter *a, Meter *b)
{
  int ia, ib;
  double tally = 0;

  g_return_val_if_fail (a != NULL, 3000);
  g_return_val_if_fail (b != NULL, 4000);

  ia = strlen (a)-1;
  ib = strlen (b)-1;

  while (ia >= 0 && ib >=0 && a[ia] && b[ia]) {
    tally += METER_ERROR (a[ia], b[ib]);
    --ia;
    --ib;
  }

  return tally;
}

/* ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** */

PyObject *
py_meter_from_phoneme_decomp (PyObject *self, PyObject *args)
{
  PyObject *py_decomp;
  Phoneme *decomp;
  Meter *m;

  if (! PyArg_ParseTuple (args, "O", &py_decomp))
    return NULL;

  decomp = phoneme_decomp_from_py (py_decomp);
  m = meter_from_phoneme_decomp (decomp);
  g_free (decomp);

  return Py_BuildValue ("s", m);
}

PyObject *
py_metric_error_left (PyObject *self, PyObject *args)
{
  Meter *a, *b;

  if (! PyArg_ParseTuple (args, "ss", &a, &b))
    return NULL;

  return Py_BuildValue ("f", metric_error_left (a, b));
}

PyObject *
py_metric_error_right (PyObject *self, PyObject *args)
{
  Meter *a, *b;

  if (! PyArg_ParseTuple (args, "ss", &a, &b))
    return NULL;

  return Py_BuildValue ("f", metric_error_right (a, b));
}
