/*
** CVS $Id: queuefunc.c,v 1.3 2001/02/08 10:53:33 zhangsz Exp $
**
** filename: queuefunc.c
** created at 2000/12/29
** by Zhang Shuzhong
** 
** loop message queue operating functions.
**
*/

#include     "./include/iptrans.h"

extern u_char warningFlag;

/*@ignore@*/
/* Read a message from loop queue. */
BOOL
iptrReadMsg(void *pbuf, void *pmsg, int max_num)
{
	in_buffer     *p;
	message_list  *msg_ptr;
    
	p = (in_buffer *) pbuf;
    	msg_ptr = (message_list *) pmsg;
//	memset(msg_ptr, EMPTY, sizeof(struct message_list));

    /* 
    ** these are some messages not to be read 
    ** while subscript of read isn't equal to subscipt of write.
    */
    if (p->msgReadSub == p->msgWriteSub)
        return FAILURE;

    memcpy(msg_ptr, &p->msgList[p->msgReadSub],
	p->msgList[p->msgReadSub].msgLength + 44);
/*message head length */
//			sizeof(struct message_list));
    /*
    ** increase READ SUBSCRIPT after got a message,
    ** set READ SUBSCRIPT to 0 while it equal to max_num.
    */
    p->msgReadSub ++;
    if (p->msgReadSub == max_num)
        p->msgReadSub = 0;
    return SUCCESS;
}

extern int SetAsciioutMsg(int flag, const char *fmt, ...);
/* Write a message to loop queue. */
BOOL 
iptrWriteMsg(void *pbuf, void *pmsg, int max_num)
{
	in_buffer     *p;
	message_list  *msg_ptr;
	int port;    
    p = (in_buffer *) pbuf;
    msg_ptr = (message_list *) pmsg;
    memcpy(&p->msgList[p->msgWriteSub], msg_ptr, 
		msg_ptr->msgLength + 44);//sizeof(struct message_list));

     p->msgWriteSub ++;

    /* 
    ** if write subscript more than max_num, 
    ** write subscript equal 0.
    */
    if (p->msgWriteSub == max_num)
        p->msgWriteSub = 0;

    /* 
    ** if message written successful,
    ** Read subscript is same as Write subscript, 
    ** then Read subsrcipt add 1.
    */
    if (p->msgReadSub == p->msgWriteSub)
    {
        (p->msgReadSub == max_num-1) ? 
            (p->msgReadSub = 0) : (p->msgReadSub ++);
        if(warningFlag){
 		    port = msg_ptr->msgDstPort;
			SetAsciioutMsg(1,"Warning!  Port: %d overflowed!\r\n",port);
        	return 0;
		}
    }
    return 1;
}


void
iptrByteRev(BYTE *pbuf, BYTE *p, size_t size)
{
	int 	i;
	char    ch;

	for (i=0; i<size; i++) {
		ch = *(pbuf++) >> 4;
		*pbuf <<= 4;
		*pbuf &= ch;
	}
	memcpy(p, pbuf, size);
}

void
iptrStrrev(char *sp)
{
	char     ch;
	ch = sp[0];
	sp[0] = sp[1];
	sp[1] = ch;
}

void
iptrByteReverse(BYTE *pbuf, BYTE *p, size_t size)
{
	
	int         i;
	char        *sp=NULL, tmpbuf[3];
	
	sp = (char *) malloc(4*size + 1);
	bzero(p, size);
	
	for (i=0; i<2*size; i+=2) {
		sprintf(tmpbuf, "%02x", *(pbuf++));
		tmpbuf[2]=0;
		iptrStrrev(tmpbuf);
		strncpy(sp+i, tmpbuf, 2);	
	}
	AsciiToBcd(pbuf, sp, 4*size);
	memcpy(p, pbuf, 2*size);
	free(sp);
}
/*@end@*/
