% var module = system.modules['/driverlib/ecap.js'];
% let Common   = system.getScript("/driverlib/Common.js");
% var nameOfModule = "ecap";
% var nameOfPeripheral = module.peripheralName;
% var device_driverlib_peripheral = system.getScript("/driverlib/device_driverlib_peripherals/" + Common.getDeviceName().toLowerCase() + "_ecap.js");
%%{
function orArrayValues(arr)
{
	//
	// Parameters
	// ----------
	// arr : array of strings
	// 		Contains all the values that are to be "OR-ed" together
	// Returns
	// -------
	// sourcesToEnableOR : string
	// 		String with all sources OR-ed, for use in masks, interrupts, etc.
	//		Puts parenthesis around all items, and newlines with tabs for 2nd,
	//		3rd, 4th, etc. items.
	//		Example: "(HRCAP_CALIBRATION_DONE
	//	 			| HRCAP_CALIBRATION_PERIOD_OVERFLOW)"
	// 
	var sourceCount = 0
	var sourcesToEnableOR = "("
	for (var sourceToEnable in arr)
	{
		if (sourceCount == 0)
		{
			sourcesToEnableOR += arr[sourceCount]
		}
		else
		{
			sourcesToEnableOR += "\n\t\t"
			sourcesToEnableOR += " | " + arr[sourceCount]
		}
		sourceCount++
	}
	sourcesToEnableOR += ")"
	return sourcesToEnableOR
}
%%}
//*****************************************************************************
//
// ECAP Configurations
//
//*****************************************************************************
void `nameOfPeripheral`_init(){
%   for(var i = 0; i < module.$instances.length; i++) 
%   {
%      var instance = module.$instances[i];
	`instance.$name`_init();
%   }
}

%if (module != null)
%{
	% /////////////////////////////////////////////////////////////////////////
	% // HRCAP SECTION 1
	% // only do this section if HRCAP is enabled:
		% for(var i = 0; i < module.$instances.length; i++) {
			% var instance = module.$instances[i];
			% var baseName = instance.$name + "_BASE";
void `instance.$name`_init(){
				% if(instance.hrcapEnable == true){
					% // get the referenced ecapBase name (like "myECAP0_BASE")
					% var ecapBaseName = instance.$name + "_BASE";
					% // use the same referenced ecapBase name to create the HRCAP instance (like "myECAP0_HR_BASE")
					% // this is also done in the board.h file, to create the global reference
					% var hrcapBaseName =  instance.$name + "_HR_BASE";
	//
	// HRCAP module configuration for `hrcapBaseName` (part of `ecapBaseName`).
	//
	// Enable High resolution clock
	//
	HRCAP_enableHighResolutionClock(`hrcapBaseName`);
	DEVICE_DELAY_US(1); // 1us delay as mentioned in HRCAP chapter of TRM
	//
	// Enable High Resolution module
	//
	HRCAP_enableHighResolution(`hrcapBaseName`);
	DEVICE_DELAY_US(1); // 1us delay as mentioned in HRCAP chapter of TRM
				% }
			% 
			% // END HRCAP SECTION 1
			% /////////////////////////////////////////////////////////////////////////
			% let instancePinmux = instance[nameOfModule];
			% if(instance.useInterrupts && instance.enableInterrupt){
	//
	// Disable ,clear all capture flags and interrupts
	//
	ECAP_disableInterrupt(`baseName`,
		(ECAP_ISR_SOURCE_CAPTURE_EVENT_1  |
		ECAP_ISR_SOURCE_CAPTURE_EVENT_2  |
		ECAP_ISR_SOURCE_CAPTURE_EVENT_3  |
		ECAP_ISR_SOURCE_CAPTURE_EVENT_4  |
		ECAP_ISR_SOURCE_COUNTER_OVERFLOW |
		ECAP_ISR_SOURCE_COUNTER_PERIOD   |
		ECAP_ISR_SOURCE_COUNTER_COMPARE));
	ECAP_clearInterrupt(`baseName`,
		(ECAP_ISR_SOURCE_CAPTURE_EVENT_1  |
		ECAP_ISR_SOURCE_CAPTURE_EVENT_2  |
		ECAP_ISR_SOURCE_CAPTURE_EVENT_3  |
		ECAP_ISR_SOURCE_CAPTURE_EVENT_4  |
		ECAP_ISR_SOURCE_COUNTER_OVERFLOW |
		ECAP_ISR_SOURCE_COUNTER_PERIOD   |
		ECAP_ISR_SOURCE_COUNTER_COMPARE));
			% }
			% if(instance.ecapMode == "CAPTURE"){
	//
	// Disables time stamp capture.
	//
	ECAP_disableTimeStampCapture(`baseName`);
			% }
	//
	// Stops Time stamp counter.
	//
	ECAP_stopCounter(`baseName`);
			% if(instance.ecapMode == "CAPTURE"){
	//
	// Sets eCAP in Capture mode.
	//
	ECAP_enableCaptureMode(`baseName`);
	//
	// Sets the capture mode.
	//
	ECAP_setCaptureMode(`baseName`,`instance.captureMode`,`instance.eventStop`);
			% }
			% else if(instance.ecapMode == "APWM") {
	//
	// Sets eCAP in APWM mode.
	//
	ECAP_enableAPWMMode(`baseName`);
			% }
			% if(instance.ecapMode == "CAPTURE"){
	//
	// Sets the Capture event prescaler.
	//
	ECAP_setEventPrescaler(`baseName`, `instance.eventPrescaler`U);
	//
	// Sets the Capture event polarity.
	//
	ECAP_setEventPolarity(`baseName`,ECAP_EVENT_1,`instance.eventOnePolarity`);
	ECAP_setEventPolarity(`baseName`,ECAP_EVENT_2,`instance.eventTwoPolarity`);
	ECAP_setEventPolarity(`baseName`,ECAP_EVENT_3,`instance.eventThreePolarity`);
	ECAP_setEventPolarity(`baseName`,ECAP_EVENT_4,`instance.eventFourPolarity`);
	//
	// Configure counter reset on events
	//
	% 		var allEcapEvents = ["ECAP_EVENT_1","ECAP_EVENT_2","ECAP_EVENT_3","ECAP_EVENT_4"]
	%			var eventCount = 0
	%			var eventStr = ""
	%			for(var anEvent in allEcapEvents){
	%				eventStr = ""+allEcapEvents[eventCount]
	%				if(instance.counterResetOnEvent.includes(eventStr)){		
	ECAP_enableCounterResetOnEvent(`baseName`,`eventStr`);	
	%				}
	%				else{
	ECAP_disableCounterResetOnEvent(`baseName`,`eventStr`);
	%				}
	%				eventCount++
	%			}
	
	//
	// Select eCAP input.
	//
	ECAP_selectECAPInput(`baseName`,`instance.ecapInput`);
				
			% }
			% if(instance.ecapMode == "APWM"){
	//
	// Set eCAP APWM period.
	//
	ECAP_setAPWMPeriod(`baseName`,`instance.apwmPeriod`U);
	//
	// Set eCAP APWM on or off time count.
	//
	ECAP_setAPWMCompare(`baseName`,`instance.apwmCompare`U);
	//
	// Set eCAP APWM polarity.
	//
	ECAP_setAPWMPolarity(`baseName`,`instance.apwmPolarity`);
			% }
	//
	// Sets a phase shift value count.
	//
	ECAP_setPhaseShiftCount(`baseName`,`instance.phaseShiftCount`U);
			% if(instance.enableLoadCounter){
	//
	// Enable counter loading with phase shift value.
	//
	ECAP_enableLoadCounter(`baseName`);
				% if(instance.loadCounter){
	//
	// Load time stamp counter.
	//
	ECAP_loadCounter(`baseName`);
				% }
			% }
			% else{
	//
	// Disable counter loading with phase shift value.
	//
	ECAP_disableLoadCounter(`baseName`);
			% }
	//
	// Configures Sync out signal mode.
	//
	ECAP_setSyncOutMode(`baseName`,`instance.syncOutMode`);
			% if( (instance.ecapMode == "CAPTURE")
			% ){
				% if(instance.resetCounters){
	//
	// Resets eCAP counters and flags.
	//
	ECAP_resetCounters(`baseName`);
				% }
			% }
			% if( (instance.ecapMode == "CAPTURE")
			% ){
				% if (instance.useDMA){
	//
	// Sets the eCAP DMA source.
	//
	ECAP_setDMASource(`baseName`,`instance.dmaSource`);
				% }
			% }
	//
	// Configures emulation mode.
	//
	ECAP_setEmulationMode(`baseName`,`instance.emulationMode`);
	//
	// Set up the source for sync-in pulse..
	//
	ECAP_setSyncInPulseSource(`baseName`,`instance.syncInPulseSource`);
			
			% var baseName = instance.$name + "_BASE";
	//
	// Starts Time stamp counter for `instance.$name`.
	//
	ECAP_startCounter(`baseName`);
			% if(instance.ecapMode == "CAPTURE"){
	//
	// Enables time stamp capture for `instance.$name`.
	//
	ECAP_enableTimeStampCapture(`baseName`);
			% }
			% if(instance.ecapMode == "CAPTURE"){
				% if(instance.reArm){
	//
	// Re-arms the eCAP module for `instance.$name`.
	//
	ECAP_reArm(`baseName`);
				% }
			% }
			% if(instance.useInterrupts && instance.enableInterrupt){
				% if(instance.ecapMode == "CAPTURE"){
					% if (instance.interruptSourceCapture.length>0)
					%{
	//
	// Enables interrupt source for `instance.$name`.
	//
	ECAP_enableInterrupt(`baseName`,`orArrayValues(instance.interruptSourceCapture)`);
					% }
				% }
				% else if(instance.ecapMode == "APWM") {
					% if (instance.interruptSourceAPWM.length>0)
					%{
	//
	// Enables interrupt source for `instance.$name`.
	//
	ECAP_enableInterrupt(`baseName`,`orArrayValues(instance.interruptSourceAPWM)`);
					% }
				% }
			% }
		% /////////////////////////////////////////////////////////////////////////
		% // HRCAP SECTION 2 (for calibration configuration)
		% // only do this section if HRCAP is enabled and calibration is enabled:
			% if(instance.hrcapEnable == true && instance.hrcapCalibrationEnable == true){
				% // get the referenced ecapBase name (like "myECAP0_BASE")
				% var ecapBaseName = instance.$name + "_BASE";
				% // use the same referenced ecapBase name to create the HRCAP instance (like "myECAP0_HR_BASE")
				% // this is also done in the board.h file, to create the global reference
				% var hrcapBaseName =  instance.$name + "_HR_BASE";
	//
	// `hrcapBaseName` Calibration Settings
	//
	// Set calibration period (register is in SYSCLK cycles), 1.6ms recommended
				% // TODO Need to make a driverlib function more flexible than "HRCAP_setCalibrationPeriod", which is locked to 1.6ms. Need to allow any given input ms.
	//
	HWREG(`hrcapBaseName` + ECAP_O_HRCALPRD) = (uint32_t) (`instance.$module.$static["chosenSYSCLK"]`e9 * (`instance.hrcapCalibrationPeriod`/1000));
	//
	// Configure in continuous calibration mode
	//
	HRCAP_setCalibrationMode(`hrcapBaseName`);
				% if (instance.enabledCalibrationInterrupts.length > 0) {
	//
	// Enable HRCAP calibration interrupts
	//
	HRCAP_enableCalibrationInterrupt(`hrcapBaseName`, `orArrayValues(instance.enabledCalibrationInterrupts)`);
				% }
	//
	// Start HR calibration
	//
	HRCAP_startCalibration(`hrcapBaseName`);
			% }
		% // END HRCAP SECTION 2
		% /////////////////////////////////////////////////////////////////////////
		       	% if(instance.ecapMode == "CAPTURE") {
				% var munitBaseName =  instance.$name + "_SIGNAL_MUNIT_BASE";
    			% if(instance.trip_selection_signalMunit != device_driverlib_peripheral.ECAP_MunitTripInputSelect[0].name) {
    ECAP_selectTripSignal(`munitBaseName`, `instance.trip_selection_signalMunit`);
            	%}
    			%if(instance.global_strobe_selection_signalMunit!=device_driverlib_peripheral.ECAP_MunitTripInputSelect[0].name) {
    ECAP_selectGlobalLoadStrobe(`munitBaseName`, `instance.global_strobe_selection_signalMunit`);
            	%}

    %for(var munitIndex in device_driverlib_peripheral.ECAP_MONITORING_UNIT) {
        % var currentMUNIT = device_driverlib_peripheral.ECAP_MONITORING_UNIT[munitIndex].name
        % var unit = (currentMUNIT).replace(/[^0-9]/g,'')
		%if(instance["enable_monitorunit"+unit]) {
    ECAP_enableSignalMonitoringUnit(`munitBaseName`, `currentMUNIT`);
    ECAP_selectMonitoringType(`munitBaseName`, `currentMUNIT`, `instance["monitorSelect_"+unit]`);
            %if(instance["minValue_"+unit] != 0){
    ECAP_configureMinValue(`munitBaseName`, `currentMUNIT`, `instance["minValue_"+unit]`);
          %}
            %if(instance["maxValue_"+unit] != 0){
    ECAP_configureMaxValue(`munitBaseName`, `currentMUNIT`, `instance["maxValue_"+unit]`);
          %}
            %if(instance["enableSyncIn_"+unit]){
    ECAP_enableShadowMinMaxRegisters(`munitBaseName`, `currentMUNIT`);
                %if(instance["forceload_"+unit]){
    ECAP_enableSoftwareSync(`munitBaseName`, `currentMUNIT`);
          %}
    ECAP_selectShadowLoadMode(`munitBaseName`, `currentMUNIT`, `instance["loadmode_"+unit]`);
                %if(instance["shadowMinValue_"+unit] != 0){
    ECAP_configureShadowMinValue(`munitBaseName`, `currentMUNIT`, `instance["shadowMinValue_"+unit]`);
          %}
                %if(instance["shadowMaxValue_"+unit] != 0){
    ECAP_configureShadowMaxValue(`munitBaseName`, `currentMUNIT`, `instance["shadowMaxValue_"+unit]`);
          %}
          %}
             %if(instance["enableDebug_"+unit]){
    ECAP_enableDebugRange(`munitBaseName`, `currentMUNIT`);
            %}
                %}
            %}
        %}
}
	%}
%}