//-----------------------------------------------------------------------------
///
/// \brief  Input Decoder
///
///         A GPInput with in Interrupt (Exti).
///
///         Can handle lot of slope calculation stuff.
///         The ISR can be kept in inherited calsses and only slopeInterrupt
///         which is called at the end of the ISR can be overloaded.
///
/// \date   20200413
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//-----------------------------------------------------------------------------


//---Includes------------------------------------------------------------------


//---Own------------------------------

#include <biwak/input.hpp>
#include <biwak/input_decoder.h>
#include <lepto/log.h>


//---Defines-------------------------------------------------------------------



//---Implementation------------------------------------------------------------


void CInputDecoderRecorder::setSlopesPerFrame(int slopesPerFrame)
{
   int _maxSlopes;
   m_slopesPerFrame=slopesPerFrame;
   _maxSlopes=slopesPerFrame;

   if(slopeTimeStamp)
      delete[] slopeTimeStamp;
#if 0
   if(m_slopeValue)
      delete[] m_slopeValue;
#endif
   slopeTimeStamp=new hrtimer_t[_maxSlopes];
#if 0
   m_slopeValue=new char[_maxSlopes];
#endif
   lAssert( slopeTimeStamp != nullptr );
#if 0
   lAssert( m_slopeValue != nullptr );
#endif

   maxSlopes=_maxSlopes;
}


int CInputDecoderRecorder::decodePulsePauseWidth(int slope, hrtimer_t pulsePauseWidth[])
{
   int i1=0;
   int diff=hrtValueToUsec( slopeTimeStamp[ slope +1 ]-slopeTimeStamp[slope] );

   while(pulsePauseWidth[i1])
   {
      if( abs(pulsePauseWidth[i1]-diff) < pulseTolerance )
         return(i1);
      i1++;
   }
   return(i1);
};


int CInputDecoderRecorder::pulseWidth(int slope) const
{
   hrtimer_t hrtDiff=slopeTimeStamp[ slope +1 ]-slopeTimeStamp[slope];

   /*
   if(hrtDiff<0)
      exception("Negative diff", slope);
   */
   //int diff=hrtValueToUsec();

   return( hrtValueToUsec( hrtDiff ) );
};

//---fin-----------------------------------------------------------------------
