/*
 * helper.c
 *
 *  Created on: 21-07-2016
 *      Author: KJ
 */

#include "tdefs.h"
#include "logman.h"
#include "dev_ctrl.h"
#include "helper.h"
#include "config.h"

enum rej_ost status_rej;

int set_bit_ptr(u32 io,void *bit_ptr, u8 *bit_no)
{
	u8 *bptr;

	bptr = (u8*)log_manager.nets_data + (io >> 3);
	*bit_no = io & 0x07;

	if((u8*)bptr > (log_manager.nets_data + sizeof(log_manager.nets_data) - sizeof(u8)))
		return -1;

	*(u32 *)bit_ptr=(u32)bptr;

	return 0;
}

int set_bit_ptr_mask(u32 io,void *bit_ptr, u8 *mask)
{
	u8 *bptr;

	bptr = (u8*)log_manager.nets_data + (io >> 3);
	*mask = (1<<(io & 0x07));

	if((u8*)bptr > (log_manager.nets_data + sizeof(log_manager.nets_data) - sizeof(u8)))
		return -1;

	*(u32 *)bit_ptr=(u32)bptr;

	return 0;
}

int set_bit_ptr_struct(u32 io,struct binary_io *b)
{
	b->ptr = (u8*)log_manager.nets_data + (io >> 3);
	b->bit_mask = (1<<(io & 0x07));

	if((u8*)b->ptr > (log_manager.nets_data + sizeof(log_manager.nets_data) - sizeof(u8)))
		return -1;

	return 0;
}

int set_float_ptr(u32 io,void *float_ptr)
{
	float *fptr;

	fptr = (float *)(log_manager.nets_data + (io >> 3));
	if((u8 *)fptr > (log_manager.nets_data + sizeof(log_manager.nets_data) - sizeof(float)))
		return -1;

	*(u32 *)float_ptr=(u32)fptr;

	return 0;
}

int set_pointer_out_ptr(u32 io, u32 *pointer_ptr)
{
	u32 *f_ptr;

	f_ptr = (u32 *)(log_manager.nets_data + (io >> 3));
	if((u8 *)f_ptr > (log_manager.nets_data+sizeof(log_manager.nets_data) - sizeof(void *)))
		return -1;

	*f_ptr = (u32)pointer_ptr;
	return 0;
}

int set_pointer_in_ptr(u32 io, u32 *pointer_ptr)
{
	u32 *f_ptr;

	f_ptr = (u32 *)(log_manager.nets_data + (io >> 3));
	if((u8 *)f_ptr > (log_manager.nets_data+sizeof(log_manager.nets_data) - sizeof(void *)))
		return -1;

	if((u32)f_ptr == (u32)&log_manager.nets_data[0]) // if pointer connected to net '0'
		*(u32 *)pointer_ptr=(u32)f_ptr;
	else
		*(u32 *)pointer_ptr=(u32)*f_ptr;

	if(!*f_ptr)
		return -1;

	return 0;
}

void sprawdz_P(u8 *Wy, u8 P, u8 O, short *lp, short iz, short io)
{
	if (*Wy)
	{
		if (O) *lp +=LOOP_CYCLE_MS; else *lp -= LOOP_CYCLE_MS;
		if (*lp < 0) *lp =0;
		if (*lp >= io)
		{
			*lp = 0;
			*Wy = 0;
		}
	} else {
		if (P) *lp +=LOOP_CYCLE_MS; else *lp -=LOOP_CYCLE_MS;
		if (*lp < 0) *lp =0;
		if (*lp >= iz)
		{
			*Wy = 1;
			*lp = 0;
		}
	}

}

void sprawdz_P_100(u8 *Wy, u8 P, u8 O, short *lp, short iz, short io)
{
	if (*Wy)
	{
		if (O) *lp +=1; else *lp -= 1;
		if (*lp < 0) *lp =0;
		if (*lp >= io)
		{
			*lp = 0;
			*Wy = 0;
		}
	} else {
		if (P) *lp +=1; else *lp -=1;
		if (*lp < 0) *lp =0;
		if (*lp >= iz)
		{
			*Wy = 1;
			*lp = 0;
		}
	}
}

int czy_test_R()
{
	return (dev_ctrl_state & DEV_CTRL_STATE_TEST_LOG);
}
