/*******************************************************************************
 *  div_sh48.c - Divide a 48 bit number by a 16 bit number, with a prescaling shift.
 *
 *  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 div_sh48(int16_t x[3], int sh, int16_t y)
{
    /* Preshift a 48 bit integer upwards by a specified amount. Then divide
       a 16 bit integer into the shifted 48 bit one. Expect the answer to be
       no greater than 32 bits, so return the answer as a 32 bit integer.
       A somewhat domain specific divide operation, but pretty useful when
       handling dot products. */
    int32_t x1;
    int32_t z;
    int16_t xx[3];
    
    /* Avoid any divide by zero trouble */
    if (y == 0)
        return 0;

    xx[0] = x[0];
    xx[1] = x[1];
    xx[2] = x[2];
    shift48(xx, sh);
    x1 = xx[2]%y;
    x1 <<= 16;
    x1 |= (uint16_t) xx[1];
    z = x1/y;
    x1 = x1%y;
    x1 <<= 16;
    x1 |= (uint16_t) xx[0];
    z = (z << 16) + x1/y;
    return z;
}
