/*
 * mkstream.c
 *
 *  Created on: 22-03-2019
 *      Author: Krzysztof Jakubczyk
 */

#include <math.h>

#include "tdefs.h"
#include "misc.h"
#include "eth.h"
#include "helper.h"
#include "mkstream.h"
#include "analog_in.h"

int mkstream_initlog(void *arguments, void *logic)
{
	struct mkstream_args *args = (struct mkstream_args *)arguments;
	struct mkstream_logic *log = (struct mkstream_logic *)logic;
	u8 i;

	if(set_float_ptr(args->io.A1L1_float_in,&log->A[0]))
		return -1;
	if(set_float_ptr(args->io.A1L2_float_in,&log->A[1]))
		return -1;
	if(set_float_ptr(args->io.A1L3_float_in,&log->A[2]))
		return -1;
	if(set_pointer_in_ptr(args->io.A1_params_ptr_in,(u32 *)&log->A_params))
		return -1;

	if(set_pointer_out_ptr(args->io.stream_ptr_out,(u32*)&log->stream))
		return -1;

	if(set_float_ptr(args->io.bits_float_in,(float *)&log->bits))
		return -1;

	for(i=0;i<8;i++)
		if(set_bit_ptr_struct(args->io.gpbit_in[i],&log->gpbit[i]))
			return -1;

	if(set_bit_ptr_struct(args->io.valid_sync_in,&log->valid_sync))
		return -1;

	if(set_float_ptr(args->io.A1L1_prev_float_in,&log->A_prev[0]))
		return -1;
	if(set_float_ptr(args->io.A1L2_prev_float_in,&log->A_prev[1]))
		return -1;
	if(set_float_ptr(args->io.A1L3_prev_float_in,&log->A_prev[2]))
		return -1;

	log->stream.hdr[0] = 'T';
	log->stream.hdr[1] = 'Z';
	log->stream.addr = args->params.addr;

	if(args->params.addr>=ETH_MAX_RECV_STREAMS)
	{
		log->stream.addr = 0;
		return -1;
	}

	for(i=0;i<3;i++)
		log->mul[i]=log->A_params->znam_pierw;/* / log->A_params->znam_wtor*/

	return 0;
}

void mkstream(void *arguments, void *logic)
{
	struct mkstream_logic *log = (struct mkstream_logic *)logic;
	struct mkstream_args *args = (struct mkstream_args *)arguments;

	u32 i;

	for(i=0;i<3;i++)
	{
		log->stream.A[i]=*log->A[i] * log->mul[i];
		log->stream.A_prev[i]=*log->A_prev[i] * log->mul[i];
	}

	log->stream.bits = *log->bits & 0xFF;

	for(i=0;i<8;i++)
		if(check_struct(&log->gpbit[i]))
			log->stream.bits|=(256<<i);

	log->stream.addr = args->params.addr;
	log->stream.cksum=CKSUM_IV;
	log->stream.sample_stamp=bus_an_cur_timestamp;
	if(!check_struct(&log->valid_sync))
		log->stream.sample_stamp|=STREAM_NO_SYNC;

	for(i=0;i<sizeof(struct stream_frame) - 1;i++)
		log->stream.cksum+=*((u8*)&log->stream+i);
}
