#include "queue.h"

static int read_d;				/*!< Read index points to the place in the queue that has already been read */
static int write_d;				/*!< The write index points to the place where the next write in the queue will take place. */

static unsigned int nexaQueueBuffer[NEXA_QUEUE_SIZE];


void  rcvInitQueue(  ) {
    
	read_d = 0;
	write_d = 1;
}

unsigned int getQueueUsed() {
  
  return (write_d-read_d);
}

unsigned char rcvEnQueue( unsigned int value ) {
    
	// Is the queue full ?
	if( write_d == read_d )
	{
		return 0u;
	}
    
	// Make the data copy
	nexaQueueBuffer[write_d] = value;
    
	// Increment the write position
	write_d++;
	if( write_d == NEXA_QUEUE_SIZE ) write_d=0;
    
	return 1u;
}

unsigned char  rcvDeQueue( unsigned int *value ) {
    
	int writePos = write_d;
    
	// Pseudo writepos
	if( writePos < read_d || writePos == read_d ) writePos += NEXA_QUEUE_SIZE;
    
	// The queue is empty ?
	if( writePos == ( read_d + 1 ) )
	{
		return 0u;
	}
    
	// Increment the read position
	read_d++;
	if( read_d == NEXA_QUEUE_SIZE ) read_d=0; 
    
	// Make the data copy
	*value = nexaQueueBuffer[read_d];
    
	return 1u;
}

// This function rolls back the latest inserted entry
unsigned char rcvRollbackQueue() {

	// Is the queue empty ?
	if( write_d == ( read_d + 1 ) )
	{
		return 0u; // No rollback
	}
	
	if( write_d == 0 ) {
		write_d = NEXA_QUEUE_SIZE - 1;
	}
	else {
		write_d--;
	}

	return 1u;
}


