/* [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved. */
# include "genlib.h"

extern void iround();
extern void ifloor();

void mexFunction(int nlhs,       mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{

# define MEXNAME iflooriroundmex

 /* k = iflooriroundmex(t,x,w); */

# define K  pout[0]

# define T  prhs[0] /* double, non-empty */
# define X  prhs[1] /* double */
# define W  prhs[2] /* numeric, scalar */

 CHECK_NARGIN_EQ(3);

 CHECK_DOUBLE(T);
 if (mxIsEmpty(T)) mexErrMsgIdAndTxt("iflooriroundmex:emptyT","ifloor/iround cannot work with an empty table T");
 CHECK_DOUBLE(X);
 CHECK_NUMERIC(W);
 CHECK_SCALAR(W);

 CHECK_NARGOUT_LE(1);

 mxArray *pout[1];

 int		*k,sizeX,sizeT;
 register int	i;
 
 /* sizes */
 sizeT = mxGetNumberOfElements(T);
 sizeX = mxGetNumberOfElements(X);

 /* memory allocation */
 K = mxCreateDoubleMatrix(mxGetM(X), mxGetN(X), mxREAL);
 k = (int *)mxCalloc(sizeX, sizeof(int));

 /* do the work */
 if (mxGetScalar(W))
  iround(k,mxGetPr(T),sizeT,mxGetPr(X),sizeX);
 else
  ifloor(k,mxGetPr(T),sizeT,mxGetPr(X),sizeX);
  
 /* convert result in double and index starting at 1 */
 for (i = 0; i < sizeX; i++)
  mxGetPr(K)[i] = (double)(k[i] + 1);
 mxFree(k);

 ASSIGN_PLHS;
}
