/* BSE Resampling Datahandles Test
 * Copyright (C) 2001-2002 Tim Janik
 * Copyright (C) 2006 Stefan Westerfeld
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General 
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include <bse/bsedatahandle-resample.h>
#include <bse/bsemain.h>
#include <bse/bsemathsignal.h>
#include <bse/bsedatahandle-resample.h>
#include <bse/gsldatautils.h>
#include <vector>

using std::vector;

int
main (int   argc,
      char *argv[])
{
  g_thread_init (NULL);
  bse_init_intern (&argc, &argv, NULL);
  std::set_terminate (__gnu_cxx::__verbose_terminate_handler);

  const int LEN = 44100;
  vector<float> input;
  vector<float> expected;
  for (int i = 0; i < LEN; i++)
    {
      input.push_back (sin (i * 2 * M_PI * 440.0 / 44100.0) * bse_window_blackman (double (i * 2 - LEN) / LEN));

      double j = i + 0.5; /* compute perfectly interpolated result */
      expected.push_back (sin (i * 2 * M_PI * 440.0 / 44100.0) * bse_window_blackman (double (i * 2 - LEN) / LEN));
      expected.push_back (sin (j * 2 * M_PI * 440.0 / 44100.0) * bse_window_blackman (double (j * 2 - LEN) / LEN));
    }

  GslDataHandle *ihandle = gsl_data_handle_new_mem (1, 32, 44100, 440, LEN, &input[0], NULL);
  GslDataHandle *rhandle = bse_data_handle_new_upsample2 (ihandle); 

  BseErrorType error = gsl_data_handle_open (rhandle);
  if (error)
    exit (1);

  GslDataPeekBuffer peek_buffer = { +1 /* incremental direction */, 0, };

  double worst_diff = 0.0;
  for (int64 i = 0; i < rhandle->setup.n_values; i++)
    {
      double resampled = gsl_data_handle_peek_value (rhandle, i, &peek_buffer);
      printf ("%d %f %f\n", i, expected[i], resampled);
      worst_diff = std::max (resampled - expected[i], worst_diff);
    }
  fprintf (stderr, "worst_diff = %f (%f dB)\n", worst_diff, bse_db_from_factor (worst_diff, -200));

  return 0;
}
