/* -*- c++ -*- */
/*
 * Copyright 2004 Free Software Foundation, Inc.
 * 
 * This file is part of GNU Radio
 * 
 * GNU Radio 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, or (at your option)
 * any later version.
 * 
 * GNU Radio 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 GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
/*
 * Copyright 2010, KA1RBI 
 */
/*
 * config.h is generated by configure.  It contains the results
 * of probing for features, options etc.  It should be the first
 * file included in your .cc file.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <repeater_s2v.h>
#include <gr_io_signature.h>
#include <stdio.h>
#include <string.h>

/*
 * Create a new instance of repeater_s2v and return
 * a boost shared_ptr.  This is effectively the public constructor.
 */
repeater_s2v_sptr 
repeater_make_s2v (size_t item_size, size_t nitems_per_block)
{
  return repeater_s2v_sptr (new repeater_s2v (item_size, nitems_per_block));
}

/*
 * The private constructor
 */
repeater_s2v::repeater_s2v (size_t item_size, size_t nitems_per_block)
  : gr_block ("s2v",
		   gr_make_io_signature (1, 1, item_size),
		   gr_make_io_signature (1, 1, item_size * nitems_per_block)),
	d_buf_len(0),
	d_acct (0),
	d_item_size (item_size),
	d_nitems_per_block (nitems_per_block)
{
}

/*
 * Our virtual destructor.
 */
repeater_s2v::~repeater_s2v ()
{
  // nothing else required in this example
}

static int min(int a, int b) { return ((a<b) ? a : b); }

int 
repeater_s2v::general_work (int noutput_items,
			gr_vector_int &ninput_items,
			gr_vector_const_void_star &input_items,
			gr_vector_void_star &output_items)
{
  const float *in = (const float *) input_items[0];
  unsigned char *out = (unsigned char *) output_items[0];
  size_t rc=0, amt_left=0, amt_move=0;

  amt_left = DBUFSIZE - d_buf_len;
  amt_move = min(amt_left, ninput_items[0]);
  if (amt_move > 0) {
    memcpy (&d_buf[ d_buf_len * d_item_size ], in, amt_move * d_item_size);
    d_buf_len += amt_move;
  }

  if (d_buf_len >= d_nitems_per_block) {
    memcpy (out, d_buf, d_item_size * d_nitems_per_block);
    d_buf_len = 0;
    rc = 1;
  }

  consume_each(amt_move);

  // Tell runtime system how many output items we produced.
  return rc;
}
