/*******************************************************************************
 *  mul48.c - Multiply a 32 bit number by a 16 bit number, and return the top
 *            32 bits of the result.
 *
 *  Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ 
 *  ALL RIGHTS RESERVED 
 * 
*/

#include <inttypes.h>
#include "emeter-toolkit.h"

int32_t mul48(int32_t x, int16_t y)
{
    int32_t z;
    int16_t residue;
#if defined(EMETER_TOOLKIT_SUPPORT_64BIT)
    int64_t tmp;
#endif

    z = x & 0xFFFF;
    z *= y;
    residue = z & 0xFFFF;
    z >>= 16;
    x >>= 16;
    x *= y;
    z += x;
#if defined(__GNUC__)  &&  defined(__MSP430__)
    __asm__ (
        " rla %[residue] \n"
        " rlc %A[z] \n"
        " rlc %B[z] \n"
        : [z] "+r"(z)
        : [residue] "r"(residue));
#else
    tmp = z;
    tmp <<= 1;
    if ((residue & 0x8000))
        tmp |= 1;
    z = tmp;
#endif
    return z;
}
