/* WRAPSFCN An example C-file S-function that multiplies an input by 2
   using the legacy code doubleIt.c
 
   This is the example S-function for "Writing S-Functions" - "Selecting
   an S-Function Implementation" - "Example Using S-Functions
   to Incorporate Legacy C Code" - "Using a Hand-written S-Function to
   Incorporate Legacy Code"
 
   Copyright (c) 1990-2008 by The MathWorks, Inc.
   All Rights Reserved
  */

#define S_FUNCTION_NAME wrapsfcn // S 函数名
#define S_FUNCTION_LEVEL 2       // S 函数的级别为2

#include "simstruc.h"
#include "doubleIt.h"

//extern real_T doubleIt(real_T u); // 声明外部函数

/*====================*
 * S-function methods *
 *====================*/
// 模型初始化
/* Function: mdlInitializeSizes ===============================================
 * Abstract:
 *    The sizes information is used to determine the S-function
 *    block's characteristics (number of inputs, outputs, states, etc.).
 */
static void mdlInitializeSizes (SimStruct *S) {
	ssSetNumSFcnParams(S,0);  // S函数参数个数为0
	ssSetNumContStates(S,0);  // 连续状态个数为0
	ssSetNumDiscStates(S,0);  // 离散状态个数为0
	
    /* Initialize one input port with direct feedthrough */
	if (!ssSetNumInputPorts(S,1)) return; 	// 如果输入口个数不为1，则返回
		
	ssSetInputPortWidth(S,0,1); // 第一个输入口维度
	ssSetInputPortDirectFeedThrough(S,0,1); // 第一个输入口为直馈
	
    /* Initialize one output port */
	if (!ssSetNumOutputPorts(S,1)) return; // 如果输出口个数不为1，则返回
		
	ssSetOutputPortWidth(S,0,1); // 第一个输出口维度
    /* Initialize one sample time */
	ssSetNumSampleTimes(S,1);    // 采样率个数为1
}

/* Function: mdlInitializeSampleTimes =========================================
 * Abstract:
 *    This function is used to specify the sample time(s) for your
 *    S-function. You must register the same number of sample times as
 *    specified in ssSetNumSampleTimes.
 */
// 采样时间初始化
static void mdlInitializeSampleTimes(SimStruct *S) {
	ssSetSampleTime(S,0,INHERITED_SAMPLE_TIME); // 采样时间为继承
	ssSetOffsetTime(S,0,0); // 采样时间偏移量为0
}

/* Function: mdlOutputs =======================================================
 * Abstract:
 *    Calls the doubleIt.c function to multiple the input by 2.
 */
// 模型输出
static void mdlOutputs(SimStruct *S, int tid) {
	InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
	real_T *y = ssGetOutputPortRealSignal(S,0);
	*y = doubleIt(*uPtrs[0]); //调用外部函数	
}

/* Function: mdlTerminate =====================================================
 * Abstract:
 *    In this function, you should perform any actions that are necessary
 *    at the termination of a simulation.  For example, if memory was
 *    allocated in mdlStart, this is the place to free it.
 */
// 模型结束
static void mdlTerminate(SimStruct *S){
    UNUSED_ARG(S); /* unused input argument */
}

// 以下5行代码，一般不应删除
#ifdef	MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
#include "simulink.c"      /* MEX-file interface mechanism */
#else
#include "cg_sfun.h"       /* Code generation registration function */
#endif
