#include "variable_frequency_digital_source.h"

/*
 * variable_frequency_digital_source_setup
 *
 *	This function is declared in variable_frequency_digital_source.h
 */
void variable_frequency_digital_source_setup( p_smx_dll_simulation_context context_p, p_smx_dll_device device_p ) {
	
	SMX_DLL_ERROR
		rv = SMX_DLL_NO_ERROR;

	p_variable_frequency_digital_source_default_pointers
		default_pointers_p = NULL;

	p_variable_frequency_digital_source_managed_storage
		managed_storage_p = NULL;

	// #ifdef _DEBUG
	//	if( IsDebuggerPresent() ) {
	//		DebugBreak();
	//	}
	// #endif

	// assign default pointers
	if( SMX_DLL_NO_ERROR != ( rv = variable_frequency_digital_source_assign_default_pointers( context_p, device_p ) ) ) {
		context_p->funcs->fatal_error( device_p, "Error occurred during variable_frequency_digital_source_assign_default_pointers." );
	}

	// cast unmanaged user storage
	default_pointers_p = (p_variable_frequency_digital_source_default_pointers)device_p->unmanaged_user_storage;

	// retrieve input pin pointer
	if( SMX_DLL_NO_ERROR != context_p->funcs->get_pin_by_name(device_p, "READY", SMX_DLL_DIRECTION_INPUT, &( default_pointers_p->READY_pin_p ) ) ) {
		context_p->funcs->fatal_error( device_p, "Unable to locate INPUT pin by name: READY" );
		return;
	}

	// retrieve output pin pointer
	if( SMX_DLL_NO_ERROR != context_p->funcs->get_pin_by_name(device_p, "OUT", SMX_DLL_DIRECTION_OUTPUT, &( default_pointers_p->OUT_pin_p ) ) ) {
		context_p->funcs->fatal_error( device_p, "Unable to locate OUTPUT pin by name: OUT" );
		return;
	}

	// allocate managed storage
	if( SMX_DLL_NO_ERROR != ( rv = context_p->funcs->instantiate_user_storage( device_p, sizeof( s_variable_frequency_digital_source_managed_storage ) ) ) ) {
		context_p->funcs->fatal_error(device_p, "Unable to instantiate user storage.");
		return;
	}

	// cast managed storage
	managed_storage_p = (p_variable_frequency_digital_source_managed_storage)device_p->user_storage;

	// assign defaults
	managed_storage_p->frequency         = 0;
	managed_storage_p->exponent          = 0;
	managed_storage_p->active_identifier = 1;	// this should not be zero
	managed_storage_p->period            = 0;

}
