/*******************************************************************************
 *  dc_filter16.c - DC estimation and removal for 24 bit signals
 *
 *  Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ 
 *  ALL RIGHTS RESERVED 
 * 
*/

#include <inttypes.h>
#if defined(__MSP430__)
#include <msp430.h>
#endif
#include "emeter-toolkit.h"

int32_t dc_filter24(int16_t p[3], int32_t x)
{
    int64_t tmp;

    tmp = p[2];
    tmp = tmp << 16;
    tmp |= p[1];
    tmp = tmp << 16;
    tmp |= p[0];
    tmp += ((((int32_t) x << 16) - tmp) >> 14);
    x -= (tmp >> 16);
    p[2] = (tmp >> 32) & 0xFFFF;
    p[1] = (tmp >> 16) & 0xFFFF;
    p[0] = tmp & 0xFFFF;
    return x;
}

int32_t dc_filter24_no_update(const int16_t p[3], int32_t x)
{
    int64_t tmp;

    tmp = p[2];
    tmp = tmp << 16;
    tmp |= p[1];
    x -= tmp;
    return x;
}

void dc_filter24_init(int16_t p[3], int16_t x)
{
#if !defined(__MSP430__)
    int64_t tmp;
#endif

    tmp = x << 16;
    p[2] = (tmp >> 32) & 0xFFFF;
    p[1] = (tmp >> 16) & 0xFFFF;
    p[0] = tmp & 0xFFFF;
}

int32_t dc_filter24_estimate(const int16_t p[3])
{
    int64_t tmp;

    tmp = p[2];
    tmp = tmp << 16;
    tmp |= p[1];
    tmp = tmp << 16;
    tmp |= p[0];
    return tmp >> 8;
}
