// ----------------------------------------------------------------------------
//
//  Copyright (C) 2015-2018 Fons Adriaensen <fons@linuxaudio.org>
//    
//  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 3 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, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------


#include <string.h>
#include "delay.h"


// Multiple delays, each up to 'maxdel' samples.
// Usage:
// * Call write ().
// * Call readp () as many times as required.
// The pointer returned by readp () always points
// to at least 'frag' samples without wraparound.


Delay::Delay (void):
    _data (0)
{
}


Delay::~Delay (void)
{
    delete[] _data;
}


void Delay::init (int32_t maxdel, int32_t frag)
{
    delete[] _data;
    _size = ((maxdel - 1) / frag + 2) * frag;
    _frag = frag;
    _data = new float [_size + _frag];
    reset ();
}


void Delay::reset (void)
{
    _wind = 0;
    memset (_data, 0, (_size + _frag) * sizeof (float));
}


void Delay::write (const float *p)
{
    _wind += _frag;
    if (_wind == _size)
    {
        memcpy (_data + _wind, p, _frag * sizeof (float));
	_wind = 0;
    }
    memcpy (_data + _wind, p, _frag * sizeof (float));
}

	
const float *Delay::readp (int32_t d) 	
{
    int32_t k = _wind - d;
    if (k < 0) k += _size;
    return _data + k;
}	    
    
