//>>> _using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
//<<< _using

/*  
    v.01
    Michael Auerswald <michael@908video.de>

    Reads a float[512] array of FFT values from a BassLive operator and averages 
    a specific kHz range to a 0-1 output. Not normalized (volume dependant).

    Make sure the Sample Frequency is the same as in the BassLive operator, 
    otherwise the ranges will be off.

    The range begins (FFT Start kHz) and ends at (FFT Start kHz + FFT Length kHz)

    Output is rounded to a specified number of digits so that "true zero" output is possible.
*/

namespace Framefield.Core.IDdfa304ae_db4d_4ca6_834e_cfd9d1076a50
{
    public class Class_FFTTRangeAverage : OperatorPart.Function
    {
        //>>> _inputids
        private enum InputId
        {
            RecBuffer = 0,
            FrequencyStart = 1,
            FrequencyWidth = 2,
            RoundDigits = 3,
            SampleFrequencykHz = 4
        }
        //<<< _inputids 

        //>>> _outputids
        private enum OutputId
        {
            Output = 0
        }
        //<<< _outputids
        
        public override void Dispose() {
            
        }

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) {
            //>>> _params
            var RecBuffer = inputs[(int)InputId.RecBuffer].Eval(context).Dynamic;  // Needs to be checked for null!
            var FrequencyStart = inputs[(int)InputId.FrequencyStart].Eval(context).Value;
            var FrequencyWidth = inputs[(int)InputId.FrequencyWidth].Eval(context).Value;
            var RoundDigits = inputs[(int)InputId.RoundDigits].Eval(context).Value;
            var SampleFrequencykHz = inputs[(int)InputId.SampleFrequencykHz].Eval(context).Value;
            //<<< _params

            // if no input is connected just output zero
            if (RecBuffer == null) {
                context.Value = 0;
                return context;
            }


            float kHzPerBand = SampleFrequencykHz / _SAMPLES;
            
            int bandStart = (int)Math.Floor(Math.Max(0, Math.Min(FrequencyStart*0.001f / kHzPerBand, _SAMPLES-1)));
            int bandEnd = (int)Math.Floor(Math.Max(0, Math.Min((FrequencyStart*0.001f + FrequencyWidth*0.001f) / kHzPerBand, _SAMPLES-1)));

            float sum = 0f;
            for (int i=bandStart; i <= bandEnd; i++)
            {
                sum += RecBuffer[i];
            }
            float avg = sum / (bandEnd-bandStart+1);

            context.Value = (float)Math.Round(avg, (int)RoundDigits);
            
            return context;
        }
        
        // Globals
        const int _SAMPLES = 512; // hardcoded number of fft samples
       
    }
}

