using System;
using System.Collections.Generic;
using System.Text;

namespace SampleCallback
{
    class CFPS
    {
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        static extern bool QueryPerformanceFrequency(out long lpFrequency);

        bool m_bEnoughDataExist = false;
        int m_nCurPos = 0;
        int m_nSampleCount = 0;
        long m_nFrequency = 0;
        long[] m_nCounterLog;

        public CFPS(int nSampleCount)
        {
            m_nSampleCount = nSampleCount;
            m_nCounterLog = new long[m_nSampleCount];
            QueryPerformanceFrequency(out m_nFrequency);
        }

        public void Check()
        {
            QueryPerformanceCounter(out m_nCounterLog[m_nCurPos]);
            m_nCurPos = m_nCurPos + 1;
            if (m_nSampleCount <= m_nCurPos)
            {
                m_bEnoughDataExist = true;
                m_nCurPos = 0;
            }
        }

        public double GetFPS()
        {
            int nStartPos = m_nCurPos;
            int nEndPos = m_nCurPos - 1;
            if (nEndPos < 0)
            {
                nEndPos = m_nSampleCount - 1;
            }

            int nCurSampleCount = m_nSampleCount - 1;

            if (!m_bEnoughDataExist)
            {
                nStartPos = 0;
                nEndPos = m_nCurPos - 1;
                nCurSampleCount = m_nCurPos - 1;
            }

            double dblReval = 0.0;

            if (1 <= nCurSampleCount)
            {
                long nDelta = m_nCounterLog[nEndPos] - m_nCounterLog[nStartPos];
                dblReval = nCurSampleCount * m_nFrequency / (double)nDelta;
            }

            return (dblReval);
        }

        public void Reset()
        {
            m_bEnoughDataExist = false;
            m_nCurPos = 0;
        }

    }
}
