/* Author : Rahul G rahul@smartbridges.com */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* This function takes the oid in dot format ( 1.3.6.1.4.410.... ) and encodes
 * the oid using ber rules. oid_out should be allocated by the application.. 
 * encode_oid returns the length of the encoded buffer.
 */
int encode_oid(char* oid, unsigned char* oid_out)
{
	char* ptr;
	int count=0,  oct_count=2;
	int num_val=0, oct1=0;
	char val[32];
	int last=0,len=0;	
	
	oid_out[0]=0x06 ; /* 00000110 */
	while(( (ptr=strchr(oid,'.')) != 0) || last == 0 )
	{
		if(ptr != 0)
			len=ptr-oid;
		else
			len=strlen(oid);
		
		strncpy(val,oid,len);
		val[len]='\0';
		num_val=atoi(val);
/*get the first two sub id's*/
		if(count == 0)
		{
			oct1=40* num_val;
			count++;
			oid=ptr+1;
			continue;
		}
		if(count == 1)
		{
			oct1+=num_val;
			oid_out[oct_count]=oct1;
			oct_count++;
			oid=ptr+1;
			count++;
			continue;
		}
		else
		{
			int i, loop, j;
			for(i=31;i>= 0; i--)
			{
				unsigned int mask= (num_val>>(i)) & ~(~0x0000<<1);
				if(mask)
				{
					i++;
					break;
				}
			}
			loop=  i/ 7;
			for(j=loop; j>= 0; j--)
			{
				oid_out[oct_count]= (num_val >> (j*7)) &  ~(~0x0000 << 7);
				oid_out[oct_count] |= 0x80; /* turn the msb to 1 */
				oct_count++;
			}
			oid_out[oct_count - 1] &= 0x7f; /* turn the msb back to zero for the last octect */
		}
		if(ptr != 0)
		{
			oid=ptr+1;
		}
		else
		{
			last=1;
		}
	}

//Insert the octect length	
	oid_out[1]=oct_count-2;
	return oct_count;
	
}
					
/*			
int main()
{

	unsigned char oid_ut[512];
	int k,ret;
//	ret=encode_oid("1.3.6.1.4.1.410.1.1.1.1.0",oid_ut);
	ret=encode_oid("1.2.840.113549.1",oid_ut);

	for(k=0; k< ret; k++)
		printf("%.2x ",oid_ut[k]);
	printf("\n");
	return 0;
}

*/

