#ifndef _FIRGenLowpass_H_
#define _FIRGenLowpass_H_
// #include "ipp/ipps.h"
#include <math.h>
#include <algorithm>
#define FIRGenLowpassLen      256     //滤波器长度
#define FIRGenLowpassLen2     192     //滤波器长度
 double m_dFilterCoef[FIRGenLowpassLen];   //滤波器系数
unsigned char m_dFilterBuff[FIRGenLowpassLen*2];
#define PI (3.1415926)
#define POINT_SIZE (1024)
//int m_nFIRPnt;          //?????
double m_dFIRCoef_ptr[POINT_SIZE]; //?????
float  m_fFIRCoef_ptr[POINT_SIZE];  //?????
bool GenLowpass(double rFreq, double **coef, int point,float mult)
{
    if (NULL == *coef)
    {
        *coef =(double *) m_fFIRCoef_ptr;
    }
    int nFIRPnt0 = point - 1;
    float fFIRPnt0D2 = nFIRPnt0 / 2.0f;
    for (int i = 0; i < point; i++)
    {
        m_dFIRCoef_ptr[i] = 0.54 - 0.46 * cos((2 * PI * i) / nFIRPnt0);
    }
    double dTheta = 2 * PI * rFreq, dCoefSum = 0;
 
    for (int i = 0; i < point; i++)
    {
        if (fFIRPnt0D2 == i)
        {
            m_dFIRCoef_ptr[i] *= (dTheta / PI);
        }
        else
        {
            m_dFIRCoef_ptr[i] *= (sin((i - fFIRPnt0D2) * dTheta) / ((i - fFIRPnt0D2) * PI));
        }
        dCoefSum += m_dFIRCoef_ptr[i];
    }
    mult /= dCoefSum;
    for(int i = 0; i < point; ++i)
    {
        (*coef)[i] = m_dFIRCoef_ptr[i] * mult;
    }
    return true;
}
/*****************************
*函数名：SetFIRLpCoef
*功能描述：设置滤波器参数
*参数名称：coef 滤波器系数
           length 滤波器系数长度
           rate 带宽采样率之比 = 带宽 / 采样率
           bitLen 量化位宽
           mult 带宽放大系数
*返回：成功有效滤波器长度, 失败返回0
*****************************/
int SetFIRLpCoef2(int *coef, int length, double rate, int bitLen, double mult = 1.0)
{
	int ret = 0;
    if (NULL == coef)
    {
        return ret;
    }
    double* dFIRCoef = new double[length];
	std::fill(dFIRCoef, dFIRCoef + length, 0);
     if (!GenLowpass(rate * 0.5 * mult, &dFIRCoef, length, (float ) pow(2.0, bitLen - 1) - 1))
     {
         ret = 0;
     }
    if (bitLen <= 16)
    {
        for (int i = 0; i < length; ++i) {
            if (dFIRCoef[i] >= 0)
            {
                ((short *)coef)[i] = (short)(dFIRCoef[i] + 0.5);
            }
            else
            {
                ((short *)coef)[i] = (short)(dFIRCoef[i] - 0.5);
            }
        }
        ret = length / 2;
    }
    else
    {
        for (int i = 0; i < length; ++i) {
            if (dFIRCoef[i] >= 0)
            {
                coef[i] = (int)(dFIRCoef[i] + 0.5);
            }
            else
            {
                coef[i] = (int)(dFIRCoef[i] - 0.5);
            }
        }
        ret = length;
    }
	if (dFIRCoef != nullptr)
	{
		delete[] dFIRCoef;
	}
    return ret;
}
#endif //_FIRGenLowpass_H_
