#include "nbits.h"


int BitsPerBinWord = sizeof(BinMachWord ) * CHAR_BIT ;
int BitsPerUint32 = sizeof(uint32 ) * CHAR_BIT ;

static char BitTable16[16] = {
		0,	// 	0	0
		1,	// 	1	1
		1,	//     10	2
		2,	//     11	3
		1,	//    100	4
		2,	//    101	5
		2,	//    110	6
		3,	//    111	7
		1,	//   1000	8
		2,	//   1001	9
		2,	//   1010      10
		3,	//   1011      11
		2,	//   1100      12
		3,	//   1101      13
		3,	//   1110      14
		4	//   1111      15
};
		

int NumberOnesUint32(uint32  Word)
{
	int Return = 0 ;
	for (int i = 0 ; i < BitsPerUint32; i+= 4) {
		Return += BitTable16[Word & 0xf] ; 
		Word >>= 4 ;
	}
	return Return ;
}

int NumberOnesBin(BinMachWord  Word)
{
	int Return = 0 ;
	for (int i = 0 ; i < BitsPerBinWord; i+= 4) {
		Return += BitTable16[Word & 0xf] ; 
		Word >>= 4 ;
	}
	return Return ;
}

int GetTrailingZero(uint32 Value)
{
	for (int i = 0 ; i < BitsPerUint32 ; i++) if (!(Value&1)) return i ;
	else Value >>= 1 ;
	return BitsPerUint32 ;
}

int GetTrailingOne(uint32 Value)
{
	for (int i = 0 ; i < BitsPerUint32 ; i++) if (Value&1) return i ;
	else Value >>= 1 ;
	return BitsPerUint32 ;
}

int GetLeadingZero(uint32 Value)
{
	int LeftBitIndex = BitsPerUint32 -1 ;
	uint32 Mask = 1 << LeftBitIndex ;
	for (int i = LeftBitIndex ; i > -1 ; i--)
		if (!(Value & Mask)) return i ;
		else Value <<= 1 ;
	return -1 ;
}

int GetLeadingOne(uint32 Value)
{
	int LeftBitIndex = BitsPerUint32 -1 ;
	uint32 Mask = 1 << LeftBitIndex ;
	for (int i = LeftBitIndex ; i > -1 ; i--) if (Value & Mask ) return i ;
	else Value <<= 1 ;
	return -1 ;
}

#ifdef __linux__
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void linux_core_dump()
{
	int pid = getpid();
	int myid = fork();
	while (!myid) sleep(1); // wait to be killed
	kill(pid,SIGQUIT);
	exit(0);
}
#endif
