/*
 * ddr_drv.c
 *
 *  Created on: 26-05-2017
 *      Author: KJ
 */


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

#include <string.h>
#include "rec_bin.h"
#include "rec_float.h"
#include "ddr.h"
#include "ddr_drv.h"

struct ddr_drv_logic *ddr_drv_log_ptr = NULL;

int ddr_drv_initlog(void *arguments, void *logic)
{
	struct ddr_drv_logic *log = (struct ddr_drv_logic *)logic;
	int i;

	log->an_count=0;
	log->bin_count=0;

	for(i=0;i<MAX_LOG_ELEMENTS;i++) /* find analog channels */
	{
		struct rec_float_args *args;

		args =  (struct rec_float_args *)log_manager.log_element[i].fun_args_ptr;

		if((log_manager.log_element[i].flags & FUNCTION_IS_REC_FLOAT) && (args->params.bits & REC_CHAN_ENABLED_DDR))
		{
			if((u8 *)&log->element_num[log->an_count]>(u8 *)(log_manager.buf+sizeof(log_manager.buf)-sizeof(u16)))
				return -1;

			log->element_num[log->an_count]=i|((log_manager.log_element[i].flags & FUNCTION_IS_REC_FLOAT)?ELEMENT_IS_REC_FLOAT:0);
			log->an_count++;
		}
	}

	log->sample_size=log->an_count * sizeof(u16);

	for(i=0;i<MAX_LOG_ELEMENTS;i++) /* find binary channels */
	{
		struct rec_bin_args *args;

		args =  (struct rec_bin_args *)log_manager.log_element[i].fun_args_ptr;

		if((log_manager.log_element[i].flags & FUNCTION_IS_REC_BIN) && (args->params.bits & REC_CHAN_ENABLED_DDR))
		{
			if((u8 *)&log->element_num[log->an_count+log->bin_count]>(u8 *)(log_manager.buf+sizeof(log_manager.buf)-sizeof(u16)))
				return -1;

			log->element_num[log->an_count+log->bin_count]=i;
			log->bin_count++;
		}
	}

	log->sample_size+=((log->bin_count/16)*2);
	if(log->bin_count%16)
		log->sample_size+=2;

	log->sample_size+=8; // sample number && time stamp

	if(log->sample_size>MAX_SAMPLE_SIZE)
		return -1;

	for(i=0;i<MAX_LOG_ELEMENTS;i++)
	{
		if(log_manager.log_element[i].flags & FUNCTION_IS_DDR)
		{
//			struct ddr_args *args;
			struct ddr_logic *dlog;

//			args = (struct ddr_args *)log_manager.log_element[i].fun_args_ptr;
			dlog = (struct ddr_logic *)log_manager.log_element[i].fun_log_ptr;

			if(dlog->max_reg_samples > ((DDR_REG_BANK_SIZE / log->sample_size) - 2))
				dlog->max_reg_samples = ((DDR_REG_BANK_SIZE / log->sample_size) - 2);
				//return -1;

			if((dlog->post_trigger_samples + dlog->pre_trigger_samples) > dlog->max_reg_samples)
			{
				dlog->post_trigger_samples=dlog->max_reg_samples/2;
				dlog->pre_trigger_samples=dlog->max_reg_samples/2;
			//	return -1;
			}
		}
	}

	ddr_drv_log_ptr=(struct ddr_drv_logic *)logic;

	return 0;
}

