/*=====================================================================
 * timestwo.c - contoh klasik dari dokumentasi MathWorks
 *
 * Mengalikan satu masukan skalar dengan 2.
 *
 * Kompilasi (MATLAB dengan C compiler terpasang):
 *   mex timestwo.c
 *
 * Lalu panggil dari Command Window:
 *   timestwo(21)     -> 42
 *
 * Sumber: MathWorks, "Tables of MEX Function Source Code Examples"
 * https://www.mathworks.com/help/matlab/matlab_external/
 * table-of-mex-source-code-examples.html
 *===================================================================*/
#include "mex.h"

void timestwo(double y[], double x[])
{
    y[0] = 2.0 * x[0];
}

void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    double *x, *y;
    size_t m, n;

    /* Periksa jumlah argumen masukan dan keluaran. */
    if (nrhs != 1) {
        mexErrMsgIdAndTxt("MATLAB:timestwo:invalidNumInputs",
                "One input required.");
    } else if (nlhs > 1) {
        mexErrMsgIdAndTxt("MATLAB:timestwo:maxlhs",
                "Too many output arguments.");
    }

    /* Masukan harus berupa skalar double nonkompleks. */
    m = mxGetM(prhs[0]);
    n = mxGetN(prhs[0]);
    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
        (m != 1) || (n != 1)) {
        mexErrMsgIdAndTxt("MATLAB:timestwo:inputNotScalar",
                "Input must be a noncomplex scalar double.");
    }

    /* Buat matriks keluaran (padanan zeros di sisi MATLAB). */
    plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL);

    /* Ambil pointer ke data nyata pada masukan dan keluaran. */
    x = mxGetPr(prhs[0]);
    y = mxGetPr(plhs[0]);

    /* Panggil rutin komputasi timestwo. */
    timestwo(y, x);
}
