/*
 * bin_in.c
 *
 *  Created on: 07-04-2014
 *      Author: Krzysztof Jakubczyk
 */

#include "tdefs.h"
#include "misc.h"

#include "bin_in.h"

int bin_in_initlog(void *arguments, void *logic)
{
	struct bin_in_args *args = (struct bin_in_args *)arguments;
	struct bin_in_logic *log = (struct bin_in_logic *)logic;

	log->out_ptr = log_manager.nets_data + (args->io.out >> 3);
	log->out_bit_mask = 1<<(args->io.out & 0x07);
	log->kob_ptr = log_manager.nets_data + (args->io.kob_out >> 3);
	log->kob_bit_mask = 1<<(args->io.kob_out & 0x07);

	if(args->params.card_addr>=MAX_BIN_CARDS)
	{
		if(args->params.ac_filter)
			ic->bin_ac_mask_ench[args->params.card_addr-16]|=(1<<args->params.in_num);
		else
			ic->bin_ac_mask_ench[args->params.card_addr-16]&=~(1<<args->params.in_num);
	}
	else
	{
		if(args->params.ac_filter)
			ic->bin_ac_mask[args->params.card_addr]|=(1<<args->params.in_num);
		else
			ic->bin_ac_mask[args->params.card_addr]&=~(1<<args->params.in_num);
	}

	if(log->out_ptr >= (log_manager.nets_data+sizeof(log_manager.nets_data)))
		return -1;

	if(log->kob_ptr >= (log_manager.nets_data+sizeof(log_manager.nets_data)))
		return -1;

	if(args->params.card_addr>=(MAX_BIN_CARDS * 2)) // *2 bo mwd32
		return -1;

	log->in_num_mask=(1<<args->params.in_num);
	log->card_addr_mask=(1<<args->params.card_addr);

	if(args->params.card_addr>=16)
	{
		mwd32_mask|=1<<(args->params.card_addr&0x07);
		ic->mwd32_present=1;
	}

	if(args->params.in_num>=8)
		return -1;

	return 0;
}

void bin_in(void *arguments, void *logic)
{
	struct bin_in_args *args = (struct bin_in_args *)arguments;
	struct bin_in_logic *log = (struct bin_in_logic *)logic;


	if(args->params.card_addr>=MAX_BIN_CARDS) // mwd32
	{
		if(bus_bin_data_ench[args->params.card_addr-16] & log->in_num_mask)
			*log->out_ptr|=log->out_bit_mask;
		else
			*log->out_ptr&=~log->out_bit_mask;
	}
	else
	{
		if(bus_bin_data[args->params.card_addr] & log->in_num_mask)
			*log->out_ptr|=log->out_bit_mask;
		else
			*log->out_ptr&=~log->out_bit_mask;
	}

	if(mwd32_mask & (1<<(args->params.card_addr&0x07)))
	{
		if(ic->kob_bin & (1<<(args->params.card_addr&0x07)))
			*log->kob_ptr|=log->kob_bit_mask;
		else
			*log->kob_ptr&=~log->kob_bit_mask;
	}
	else
	{
		if(ic->kob_bin & log->card_addr_mask)
			*log->kob_ptr|=log->kob_bit_mask;
		else
			*log->kob_ptr&=~log->kob_bit_mask;
	}
}
