/* [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved. */
# include "meq.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  
 /* [aqmin, qmin] = minQmex(aQ, qQ, sq[, nmin[, NF]]); */

# define MEXNAME minQmex

# define AQMIN pout[0]
# define QMIN  pout[1]

# define AQ    prhs[0]  /* double, def size=nQ */
# define QQ    prhs[1]  /* double, size=nQ */
# define SQ    prhs[2]  /* numeric, scalar */
# define NMIN  prhs[3]  /* numeric, scalar, optional */
# define NF    prhs[4]  /* numeric, scalar, optional */

 CHECK_NARGIN_GE(3);
 CHECK_NARGIN_LE(5);

 int nQ = mxGetNumberOfElements(AQ);

 CHECK_DOUBLE(AQ);
 CHECK_DOUBLE(QQ);
 CHECK_NUMEL(QQ,nQ);
 CHECK_NUMERIC(SQ);
 CHECK_SCALAR(SQ);
 if (nrhs >= 4) { CHECK_NUMERIC(NMIN);
                  CHECK_SCALAR(NMIN); }
 if (nrhs >= 5) { CHECK_NUMERIC(NF);
                  CHECK_SCALAR(NF); }

 CHECK_NARGOUT_LE(2);

 mxArray *pout[2];

 int nmin;
 double nf;
  
 if (nrhs >= 5) nf = mxGetScalar(NF);
 else           nf = NAN;
 if (nrhs >= 4) nmin = mxGetScalar(NMIN);
 else           nmin = 1;
 
 nQ = mxGetNumberOfElements(AQ);
 
 AQMIN = mxCreateDoubleMatrix(nmin,1,mxREAL);
 QMIN  = mxCreateDoubleMatrix(nmin,1,mxREAL);
 
 dminQ(mxGetPr(AQMIN), mxGetPr(QMIN), mxGetPr(AQ), mxGetPr(QQ),
       mxGetScalar(SQ), nf, nQ, nmin);

 ASSIGN_PLHS;
}
