/*
  ZynAddSubFX - a software synthesizer

  Analog Filter.h - Several analog filters (lowpass, highpass...)
  Copyright (C) 2002-2005 Nasca Octavian Paul
  Author: Nasca Octavian Paul

  Modified for rakarrack by Josep Andreu and Ryan Billing

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License
  as published by the Free Software Foundation.

  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 (version 2) for more details.

  You should have received a copy of the GNU General Public License (version 2)
  along with this program; if not, write to the Free Software Foundation,
  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

*/

#ifndef ANALOG_FILTER_H
#define ANALOG_FILTER_H

#include "../../../typedefs.h"

#ifdef SHR3D_SFX_CORE_RAKARRACK

#include "Defines.h"
#include "FilterBase.h"

class AnalogFilter : public FilterBase
{
public:
  AnalogFilter(u8 Ftype, f32 Ffreq, f32 Fq, u8 Fstages);
  void filterout(f32* smp, i32 blockSize) override;
  f32 filterout_s(f32 smp);

  void setfreq(f32 frequency) override;
  void setfreq_and_q(f32 frequency, f32 q_) override;
  void setq(f32 q_) override;
  void setSR(u32 SR);

  void settype(i32 type_);
  void setgain(f32 dBgain) override;
  void setstages(i32 stages_);
  void cleanup();
  void reversecoeffs();

  f32 H(f32 freq);	//Obtains the response for a given frequency

private:
  struct fstage
  {
    f32 c1, c2;
  } x[MAX_FILTER_STAGES + 1], y[MAX_FILTER_STAGES + 1],
    oldx[MAX_FILTER_STAGES + 1], oldy[MAX_FILTER_STAGES + 1];

  void singlefilterout(f32* smp, fstage& x, fstage& y, f32* c, f32* d, i32 blockSize);
  f32 singlefilterout_s(f32 smp, fstage& x, fstage& y, f32* c, f32* d);

  void computefiltercoefs();
  i32 type;			//The type of the filter (LPF1,HPF1,LPF2,HPF2...)
  i32 stages;			//how many times the filter is applied (0->1,1->2,etc.)
  i32 order;			//the order of the filter (number of poles)
  i32 needsinterpolation;
  i32 firsttime;
  i32 abovenq;			//this is 1 if the frequency is above the nyquist
  i32 oldabovenq;		//if the last time was above nyquist (used to see if it needs interpolation)

  u32 iSAMPLE_RATE;

  f32 freq;		//Frequency given in Hz
  f32 q;			//Q factor (resonance or Q factor)
  f32 gain = 1.0f;		//the gain of the filter (if are shelf/peak) filters

  f32 c[3]{}; //coefficients
  f32 d[3]{};

  f32 oldc[3]{};	//old coefficients(used only if some filter paremeters changes very fast, and it needs interpolation)
  f32 oldd[3]{};

  f32 xd[3], yd[3];	//used if the filter is applied more times

  f32 ifSAMPLE_RATE;
};

#endif // SHR3D_SFX_CORE_RAKARRACK

#endif
