/*
 * NDPluginDynamicROI.cpp
 *
 * Change ROI based on centroid of image
 * Author: Jeremy Mock
 *
 * Created December 2018
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <iostream>

#include <epicsTypes.h>
#include <epicsMessageQueue.h>
#include <epicsThread.h>
#include <epicsEvent.h>
#include <epicsTime.h>
#include <iocsh.h>

#include <asynDriver.h>

#include <epicsExport.h>
#include "NDPluginDriver.h"
#include "NDPluginDynamicROI.h"

#define MAX(A,B) (A)>(B)?(A):(B)
#define MIN(A,B) (A)<(B)?(A):(B)

/* Some systems do not define M_PI in math.h */
#ifndef M_PI
  #define M_PI 3.14159265358979323846
#endif

static const char *driverName="NDPluginDynamicROI";

/* The following functions were lifted directly from the 
   NDPluginDynamicROI.cpp and are used to find the centroid
   and profiles which will be used to set the ROI window
*/

template <typename epicsType>
asynStatus NDPluginDynamicROI::doComputeCentroidT(NDArray *pArray, NDStats_t *pStats)
{
    epicsType *pData = (epicsType *)pArray->pData;
    double value, *pValue, *pThresh, varX, varY, varXY;
    size_t ix, iy;
    /*Raw moments */
    double M00 = 0.0;
    double M10 = 0.0, M01 = 0.0;
    double M20 = 0.0, M02 = 0.0, M11 = 0.0;
    double M30 = 0.0, M03 = 0.0;
    double M40 = 0.0, M04 = 0.0;
    /*Central moments */
    double mu20, mu02, mu11, mu30, mu03, mu40, mu04;

    if (pArray->ndims > 2) return(asynError);
    
    for (iy=0; iy<pStats->profileSizeY; iy++) {
        for (ix=0; ix<pStats->profileSizeX; ix++) {
            value = (double)*pData++;
            pStats->profileX[profAverage][ix] += value;
            pStats->profileY[profAverage][iy] += value;
            if (value >= pStats->centroidThreshold) {
                pStats->profileX[profThreshold][ix] += value;
                pStats->profileY[profThreshold][iy] += value;
                M11 += value * ix * iy;
            }
        }
    }

    /* Normalize the average profiles and compute the centroid from them */
    pValue  = pStats->profileX[profAverage];
    pThresh = pStats->profileX[profThreshold];
    for (ix=0; ix<pStats->profileSizeX; ix++, pValue++, pThresh++) {
        M00 += *pThresh;
        M10 += *pThresh * ix;
        M20 += *pThresh * ix * ix;
        M30 += *pThresh * ix * ix * ix;
        M40 += *pThresh * ix * ix * ix * ix;
        *pValue  /= pStats->profileSizeY;
        *pThresh /= pStats->profileSizeY;
    }
    pValue  = pStats->profileY[profAverage];
    pThresh = pStats->profileY[profThreshold];
    for (iy=0; iy<pStats->profileSizeY; iy++, pValue++, pThresh++) {
        M01 += *pThresh * iy;
        M02 += *pThresh * iy * iy;
        M03 += *pThresh * iy * iy * iy;
        M04 += *pThresh * iy * iy * iy * iy;
        *pValue  /= pStats->profileSizeX;
        *pThresh /= pStats->profileSizeX;
    }

    if (M00 > 0.) {
        /* Calculate central moments */
        mu20 = M20 - (M10 * M10) / M00;
        mu02 = M02 - (M01 * M01) / M00;
        mu11 = M11 - (M10 * M01) / M00;
        mu30 = M30 - ((3 * M10 * M20) / M00) + ((2 * M10 * M10 * M10) / (M00 * M00));
        mu03 = M03 - ((3 * M01 * M02) / M00) + ((2 * M01 * M01 * M01) / (M00 * M00));
        mu40 = M40 - ((4 * M30 * M10) / M00) + ((6 * M20 * M10 * M10) / (M00 * M00)) -
             (3 * M10 * M10 * M10 * M10) / (M00 * M00 * M00);
        mu04 = M04 - ((4 * M03 * M01) / M00) + ((6 * M02 * M01 * M01) / (M00 * M00)) -
             (3 * M01 * M01 * M01 * M01) / (M00 * M00 * M00);
        /* Calculate variances */
        varX  = mu20 / M00;
        varY  = mu02 / M00;
        varXY = mu11 / M00;
        /* Scientific output parameters */
        pStats->centroidTotal = M00;
        pStats->centroidX = M10 / M00;
        pStats->centroidY = M01 / M00;
        /* Calculate sigmas */
        pStats->sigmaX = sqrt(varX);
        pStats->sigmaY = sqrt(varY);
        if ((pStats->sigmaX != 0) && (pStats->sigmaY != 0)){
            pStats->sigmaXY = varXY / (pStats->sigmaX * pStats->sigmaY);
        }
        if (varX != 0) {
            pStats->skewX = mu30  / (M00 * pow(varX, 3.0/2.0));
            pStats->kurtosisX = (mu40 / (M00 * pow(varX, 2.0))) - 3.0;
        }
        if (varY != 0) {
            pStats->skewY = mu03  / (M00 * pow(varY, 3.0/2.0));
            pStats->kurtosisY = (mu04 / (M00 * pow(varY, 2.0))) - 3.0;            
        }

        /* Calculate orientation and eccentricity */
        pStats->orientation = 0.5 * atan2((2.0 * varXY), (varX - varY));
        /* Orientation in degrees*/
        pStats->orientation  = pStats->orientation * 180 / M_PI;
        if ((mu20 + mu02) != 0){
            pStats->eccentricity = ((mu20 - mu02) * (mu20 - mu02) - 4 * mu11 * mu11) /
                                 ((mu20 + mu02) * (mu20 + mu02));
        }
    }
    return(asynSuccess);
}

asynStatus NDPluginDynamicROI::doComputeCentroid(NDArray *pArray, NDStats_t *pStats)
{
    asynStatus status;

    switch(pArray->dataType) {
        case NDInt8:
            status = doComputeCentroidT<epicsInt8>(pArray, pStats);
            break;
        case NDUInt8:
            status = doComputeCentroidT<epicsUInt8>(pArray, pStats);
            break;
        case NDInt16:
            status = doComputeCentroidT<epicsInt16>(pArray, pStats);
            break;
        case NDUInt16:
            status = doComputeCentroidT<epicsUInt16>(pArray, pStats);
            break;
        case NDInt32:
            status = doComputeCentroidT<epicsInt32>(pArray, pStats);
            break;
        case NDUInt32:
            status = doComputeCentroidT<epicsUInt32>(pArray, pStats);
            break;
        case NDFloat32:
            status = doComputeCentroidT<epicsFloat32>(pArray, pStats);
            break;
        case NDFloat64:
            status = doComputeCentroidT<epicsFloat64>(pArray, pStats);
            break;
        default:
            status = asynError;
        break;
    }
    return(status);
}

template <typename epicsType>
asynStatus NDPluginDynamicROI::doComputeProfilesT(NDArray *pArray, NDStats_t *pStats)
{
    epicsType *pData = (epicsType *)pArray->pData;
    epicsType *pCentroid, *pCursor;
    size_t ix, iy;

    if (pArray->ndims > 2) return(asynError);

    /* Compute the X and Y profiles at the centroid and cursor positions */
    iy = (size_t) (pStats->centroidY + 0.5);
    iy = MAX(iy, 0);
    iy = MIN(iy, pStats->profileSizeY-1);
    pCentroid = pData + iy*pStats->profileSizeX;
    iy = pStats->cursorY;
    iy = MAX(iy, 0);
    iy = MIN(iy, pStats->profileSizeY-1);
    pCursor = pData + iy*pStats->profileSizeX;
    for (ix=0; ix<pStats->profileSizeX; ix++) {
        pStats->profileX[profCentroid][ix] = *pCentroid++;
        pStats->profileX[profCursor][ix]   = *pCursor++;
    }
    ix = (size_t) (pStats->centroidX + 0.5);
    ix = MAX(ix, 0);
    ix = MIN(ix, pStats->profileSizeX-1);
    pCentroid = pData + ix;
    ix = pStats->cursorX;
    ix = MAX(ix, 0);
    ix = MIN(ix, pStats->profileSizeX-1);
    pCursor = pData + ix;
    for (iy=0; iy<pStats->profileSizeY; iy++) {
        pStats->profileY[profCentroid][iy] = *pCentroid;
        pStats->profileY[profCursor][iy]   = *pCursor;
        pCentroid += pStats->profileSizeX;
        pCursor   += pStats->profileSizeX;
    }

    return(asynSuccess);
}

asynStatus NDPluginDynamicROI::doComputeProfiles(NDArray *pArray, NDStats_t *pStats)
{
    asynStatus status;

    switch(pArray->dataType) {
        case NDInt8:
            status = doComputeProfilesT<epicsInt8>(pArray, pStats);
            break;
        case NDUInt8:
            status = doComputeProfilesT<epicsUInt8>(pArray, pStats);
            break;
        case NDInt16:
            status = doComputeProfilesT<epicsInt16>(pArray, pStats);
            break;
        case NDUInt16:
            status = doComputeProfilesT<epicsUInt16>(pArray, pStats);
            break;
        case NDInt32:
            status = doComputeProfilesT<epicsInt32>(pArray, pStats);
            break;
        case NDUInt32:
            status = doComputeProfilesT<epicsUInt32>(pArray, pStats);
            break;
        case NDFloat32:
            status = doComputeProfilesT<epicsFloat32>(pArray, pStats);
            break;
        case NDFloat64:
            status = doComputeProfilesT<epicsFloat64>(pArray, pStats);
            break;
        default:
            status = asynError;
        break;
    }
    return(status);
}


/** Callback function that is called by the NDArray driver with new NDArray data.
  * Does image statistics.
  * \param[in] pArray  The NDArray from the callback.
  */
void NDPluginDynamicROI::processCallbacks(NDArray *pArray)
{
    /* This function does array statistics.
     * It is called with the mutex already locked.  It unlocks it during long calculations when private
     * structures don't need to be protected.
     */
    int dataType;
    NDDimension_t dims[2], tempDim, *pDim;
    size_t userDims[ND_ARRAY_MAX_DIMS];
    int dim;
    NDStats_t stats, *pStats=&stats, statsTemp, *pStatsTemp=&statsTemp;
    int computeCentroid, computeProfiles;
    size_t sizeX=0, sizeY=0;
    int itemp;
    NDArrayInfo arrayInfo;
    double *pData;
    size_t i;
    static const char* functionName = "NDPluginDynamicROI::processCallbacks";
    NDArray *pOutput;
    int tempOffset, tempMax, tempSize;
    int enableDim[2];

    /* Call the base class method */
    NDPluginDriver::beginProcessCallbacks(pArray); //ADCore 3.2  

    // This plugin only works with 1-D or 2-D arrays
    if ((pArray->ndims < 1) || (pArray->ndims > 2)) {
        asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
          "%s: error, number of array dimensions must be 1 or 2\n",
          functionName);
    } 

    memset(dims, 0, sizeof(NDDimension_t) * ND_ARRAY_MAX_DIMS);
    /* Get information about the array */
    pArray->getInfo(&arrayInfo);
    getIntegerParam(NDPluginDynamicROIComputeCentroid,    &computeCentroid);
    getIntegerParam(NDPluginDynamicROIComputeProfiles,    &computeProfiles);
    getIntegerParam(NDPluginDynamicROICursorX, &itemp); pStats->cursorX = itemp;
    getIntegerParam(NDPluginDynamicROICursorY, &itemp); pStats->cursorY = itemp;
    getDoubleParam (NDPluginDynamicROICentroidThreshold,  &pStats->centroidThreshold);
    getIntegerParam(NDPluginDynamicROIDim0Enable,   &enableDim[0]);
    getIntegerParam(NDPluginDynamicROIDim1Enable,   &enableDim[1]);
    getIntegerParam(NDPluginDynamicROIDataType,     &dataType);
    if (pArray->ndims > 0) sizeX = pArray->dims[0].size;
    if (pArray->ndims == 1) sizeY = 1;
    if (pArray->ndims > 1)  sizeY = pArray->dims[1].size;

    if (computeCentroid || computeProfiles) {
        pStats->profileSizeX = sizeX;
        setIntegerParam(NDPluginDynamicROIProfileSizeX,  (int)pStats->profileSizeX);
        for (i=0; i<MAX_PROFILE_TYPES; i++) {
            pStats->profileX[i] = (double *)calloc(pStats->profileSizeX, sizeof(double));
        }
        pStats->profileSizeY = sizeY;
        setIntegerParam(NDPluginDynamicROIProfileSizeY, (int)pStats->profileSizeY);
        for (i=0; i<MAX_PROFILE_TYPES; i++) {
            pStats->profileY[i] = (double *)calloc(pStats->profileSizeY, sizeof(double));
        }
    }
    // Release the lock.  While it is released we cannot access the parameter library or class member data.
    this->unlock();        

    if (computeCentroid) {
        doComputeCentroid(pArray, pStats);
    }
    if (computeProfiles) {
        doComputeProfiles(pArray, pStats);
    }    
    // Take the lock again.

    this->lock();
   
    if (computeCentroid) {
        setDoubleParam(NDPluginDynamicROICentroidTotal, pStats->centroidTotal);
        setDoubleParam(NDPluginDynamicROICentroidX,     pStats->centroidX);
        setDoubleParam(NDPluginDynamicROICentroidY,     pStats->centroidY);
        setDoubleParam(NDPluginDynamicROISigmaX,        pStats->sigmaX);
        setDoubleParam(NDPluginDynamicROISigmaY,        pStats->sigmaY);
        setDoubleParam(NDPluginDynamicROISigmaXY,       pStats->sigmaXY);
    }
    userDims[0] = arrayInfo.xDim;
    userDims[1] = arrayInfo.yDim;
    userDims[2] = 0;
    for(dim=0; dim < pArray->ndims; dim++){
      dims[dim].binning = pArray->dims[dim].binning;
      dims[dim].reverse = pArray->dims[dim].reverse;
    }
    size_t newDimSize;
    if (computeCentroid){
    if (enableDim[0]) {
      /* Make sure dimensions are valid, fix them if they are not */
      pDim = &dims[0];
      newDimSize = pArray->dims[userDims[0]].size;
      tempSize = requestedSize_[0];
      if (tempSize > (int)newDimSize) {
        tempSize = (int)newDimSize;
      }
      tempOffset = (int)pStats->centroidX - ((int)tempSize/2);
      tempOffset = MAX(tempOffset, 0);
      tempMax = tempOffset + tempSize;
      if (tempMax > (int)newDimSize){
        tempOffset = newDimSize - tempSize;
      }        
      pDim->offset  = tempOffset;
      pDim->size    = MAX(tempSize, 1);
    } else{
      /* Make sure dimensions are valid, fix them if they are not */
      pDim = &dims[0];
      pDim->offset  = 0;
      pDim->size    = pArray->dims[userDims[0]].size;
    }
    if (enableDim[1]) {
      newDimSize = pArray->dims[userDims[1]].size;
      pDim = &dims[1];
      tempSize = requestedSize_[1];
      if (tempSize > (int)newDimSize) {
        tempSize = (int)newDimSize;
      }
      tempOffset = (int)pStats->centroidY - ((int)tempSize/2);
      tempOffset = MAX(tempOffset, 0);
      tempMax = tempOffset + tempSize;
      if (tempMax > (int)newDimSize){
        tempOffset = newDimSize - tempSize;
      }        
      pDim->offset  = tempOffset;
      pDim->size    = MAX(tempSize, 1);
    } else {
      pDim = &dims[1];
      pDim->offset  = 0;
      pDim->size    = pArray->dims[userDims[1]].size;
    }
    }
    else {
      /* Make sure dimensions are valid, fix them if they are not */
      pDim = &dims[0];
      pDim->offset  = 0;
      pDim->size    = pArray->dims[userDims[0]].size;

      pDim = &dims[1];
      pDim->offset  = 0;
      pDim->size    = pArray->dims[userDims[1]].size;
    }      
  /* Update the parameters that may have changed */
    setIntegerParam(NDPluginDynamicROIDim0MaxSize, 0);
    setIntegerParam(NDPluginDynamicROIDim1MaxSize, 0);
    if (pArray->ndims > 0) {
        pDim = &dims[0];
        setIntegerParam(NDPluginDynamicROIDim0MaxSize, (int)pArray->dims[userDims[0]].size);
        setIntegerParam(NDPluginDynamicROIDim0Min,  (int)pDim->offset);
        setIntegerParam(NDPluginDynamicROIDim0Size, (int)pDim->size);
    }
    if (pArray->ndims > 1) {
        pDim = &dims[1];
        setIntegerParam(NDPluginDynamicROIDim1MaxSize, (int)pArray->dims[userDims[1]].size);
        setIntegerParam(NDPluginDynamicROIDim1Min,  (int)pDim->offset);
        setIntegerParam(NDPluginDynamicROIDim1Size, (int)pDim->size);
    }
    this->unlock();    
    /* Extract this ROI from the input array.  The convert() function allocates
     * a new array and it is reserved (reference count = 1) */
    if (dataType == -1) {
        dataType     = (int)pArray->dataType;
    }
    
    /*printf("%s \n","Can we at least get here");
    NDArrayInfo pArrayInfo;
    NDArrayInfo pOutputInfo;
    printf("%s \n","Info Initialized");
    pArray->getInfo(&pArrayInfo);
    pOutput->getInfo(&pOutputInfo);
    printf("%s \n","Got info");
    printf("pArrayX: %i\n",pArrayInfo.xSize);
    printf("pArrayY: %i\n",pArrayInfo.ySize);
    printf("pOutputX: %i\n",pOutputInfo.xSize);
    printf("pOutputY: %i\n",pOutputInfo.ySize);
    printf("dims: %i\n",dims);*/
    this->pNDArrayPool->convert(pArray,&pOutput,(NDDataType_t)dataType,dims);
    this->lock();
    /* Set the image size of the ROI image data */
    setIntegerParam(NDArraySizeX, 0);
    setIntegerParam(NDArraySizeY, 0);
    setIntegerParam(NDArraySizeZ, 0);
    if (pOutput->ndims > 0) setIntegerParam(NDArraySizeX, (int)pOutput->dims[userDims[0]].size);
    if (pOutput->ndims > 1) setIntegerParam(NDArraySizeY, (int)pOutput->dims[userDims[1]].size);
    if (computeProfiles) {
      doCallbacksFloat64Array(pStats->profileX[profAverage],   pStats->profileSizeX, NDPluginDynamicROIProfileAverageX, 0);
      doCallbacksFloat64Array(pStats->profileY[profAverage],   pStats->profileSizeY, NDPluginDynamicROIProfileAverageY, 0);
      doCallbacksFloat64Array(pStats->profileX[profThreshold], pStats->profileSizeX, NDPluginDynamicROIProfileThresholdX, 0);
      doCallbacksFloat64Array(pStats->profileY[profThreshold], pStats->profileSizeY, NDPluginDynamicROIProfileThresholdY, 0);
      doCallbacksFloat64Array(pStats->profileX[profCentroid],  pStats->profileSizeX, NDPluginDynamicROIProfileCentroidX, 0);
      doCallbacksFloat64Array(pStats->profileY[profCentroid],  pStats->profileSizeY, NDPluginDynamicROIProfileCentroidY, 0);
      doCallbacksFloat64Array(pStats->profileX[profCursor],    pStats->profileSizeX, NDPluginDynamicROIProfileCursorX, 0);
      doCallbacksFloat64Array(pStats->profileY[profCursor],    pStats->profileSizeY, NDPluginDynamicROIProfileCursorY, 0);
    }
    if (computeCentroid || computeProfiles) {
        for (i=0; i<MAX_PROFILE_TYPES; i++) {
            free(pStats->profileX[i]);
            free(pStats->profileY[i]);
        }
    }
    NDPluginDriver::endProcessCallbacks(pOutput, false, true); // ADCore 3.2
    callParamCallbacks();
}

/** Called when asyn clients call pasynInt32->write().
  * This function performs actions for some parameters.
  * For all parameters it sets the value in the parameter library and calls any registered callbacks..
  * \param[in] pasynUser pasynUser structure that encodes the reason and address.
  * \param[in] value Value to write. */
asynStatus NDPluginDynamicROI::writeInt32(asynUser *pasynUser, epicsInt32 value)
{
    int function = pasynUser->reason;
    asynStatus status = asynSuccess;
    static const char *functionName = "writeInt32";


    /* Set the parameter in the parameter library. */
    status = (asynStatus) setIntegerParam(function, value);
    if (function == NDPluginDynamicROICursorX) {
        if (pPrevInputArray_) {
            processCallbacks(pPrevInputArray_);
        }
    } else if (function == NDPluginDynamicROICursorY) {
        if (pPrevInputArray_) {
            processCallbacks(pPrevInputArray_);
        }
    } else if (function == NDPluginDynamicROIDim0Min) {
        requestedOffset_[0] = value;
    } else if (function == NDPluginDynamicROIDim1Min) {
        requestedOffset_[1] = value;
    } else if (function == NDPluginDynamicROIDim0Size) {
        requestedSize_[0] = value;
    } else if (function == NDPluginDynamicROIDim1Size) {
        requestedSize_[1] = value;
    } else {
        /* If this parameter belongs to a base class call its method */
        if (function < FIRST_NDPLUGIN_STATS_PARAM) 
            status = NDPluginDriver::writeInt32(pasynUser, value);
    }
    
    /* Do callbacks so higher layers see any changes */
    status = (asynStatus) callParamCallbacks();
    
    if (status) 
        epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize, 
                  "%s:%s: status=%d, function=%d, value=%d", 
                  driverName, functionName, status, function, value);
    else        
        asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, 
              "%s:%s: function=%d, value=%d\n", 
              driverName, functionName, function, value);
    return status;
}

/** Called when asyn clients call pasynFloat64->write().
  * This function performs actions for some parameters.
  * For all parameters it sets the value in the parameter library and calls any registered callbacks..
  * \param[in] pasynUser pasynUser structure that encodes the reason and address.
  * \param[in] value Value to write. */
asynStatus  NDPluginDynamicROI::writeFloat64(asynUser *pasynUser, epicsFloat64 value)
{
    int function = pasynUser->reason;
    asynStatus status = asynSuccess;
    int computeCentroid;
    static const char *functionName = "writeFloat64";

    /* Set the parameter and readback in the parameter library.  This may be overwritten when we read back the
     * status at the end, but that's OK */
    status = setDoubleParam(function, value);
    if (function == NDPluginDynamicROICentroidThreshold) {
        getIntegerParam(NDPluginDynamicROIComputeCentroid, &computeCentroid);
        if (computeCentroid && pPrevInputArray_) {
            processCallbacks(pPrevInputArray_);
        }
    } 
    else {
        /* If this parameter belongs to a base class call its method */
        if (function < FIRST_NDPLUGIN_STATS_PARAM) status = NDPluginDriver::writeFloat64(pasynUser, value);
    }

    /* Do callbacks so higher layers see any changes */
    callParamCallbacks();
    if (status) 
        asynPrint(pasynUser, ASYN_TRACE_ERROR, 
              "%s:%s: error, status=%d function=%d, value=%f\n", 
              driverName, functionName, status, function, value);
    else        
        asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, 
              "%s:%s: function=%d, value=%f\n", 
              driverName, functionName, function, value);
    return status;
}



/** Constructor for NDPluginDynamicROI; most parameters are simply passed to NDPluginDriver::NDPluginDriver.
  * After calling the base class constructor this method sets reasonable default values for all of the
  * parameters.
  * \param[in] portName The name of the asyn port driver to be created.
  * \param[in] queueSize The number of NDArrays that the input queue for this plugin can hold when
  *            NDPluginDriverBlockingCallbacks=0.  Larger queues can decrease the number of dropped arrays,
  *            at the expense of more NDArray buffers being allocated from the underlying driver's NDArrayPool.
  * \param[in] blockingCallbacks Initial setting for the NDPluginDriverBlockingCallbacks flag.
  *            0=callbacks are queued and executed by the callback thread; 1 callbacks execute in the thread
  *            of the driver doing the callbacks.
  * \param[in] NDArrayPort Name of asyn port driver for initial source of NDArray callbacks.
  * \param[in] NDArrayAddr asyn port driver address for initial source of NDArray callbacks.
  * \param[in] maxBuffers The maximum number of NDArray buffers that the NDArrayPool for this driver is
  *            allowed to allocate. Set this to -1 to allow an unlimited number of buffers.
  * \param[in] maxMemory The maximum amount of memory that the NDArrayPool for this driver is
  *            allowed to allocate. Set this to -1 to allow an unlimited amount of memory.
  * \param[in] priority The thread priority for the asyn port driver thread if ASYN_CANBLOCK is set in asynFlags.
  * \param[in] stackSize The stack size for the asyn port driver thread if ASYN_CANBLOCK is set in asynFlags.
  * \param[in] maxThreads The maximum number of threads this driver is allowed to use. If 0 then 1 will be used.
  */
NDPluginDynamicROI::NDPluginDynamicROI(const char *portName, int queueSize, int blockingCallbacks,
                         const char *NDArrayPort, int NDArrayAddr,
                         int maxBuffers, size_t maxMemory,
                         int priority, int stackSize, int maxThreads)
    /* Invoke the base class constructor */
    : NDPluginDriver(portName, queueSize, blockingCallbacks,
                   NDArrayPort, NDArrayAddr, 1, maxBuffers, maxMemory,
                   asynInt32ArrayMask | asynFloat64ArrayMask | asynGenericPointerMask,
                   asynInt32ArrayMask | asynFloat64ArrayMask | asynGenericPointerMask,
                   0, 1, priority, stackSize, maxThreads)
{
    //static const char *functionName = "NDPluginDynamicROI";

    /* Centroid */
    createParam(NDPluginDynamicROIComputeCentroidString,   asynParamInt32,      &NDPluginDynamicROIComputeCentroid);
    createParam(NDPluginDynamicROICentroidThresholdString, asynParamFloat64,    &NDPluginDynamicROICentroidThreshold);
    createParam(NDPluginDynamicROICentroidTotalString,     asynParamFloat64,    &NDPluginDynamicROICentroidTotal);
    createParam(NDPluginDynamicROICentroidXString,         asynParamFloat64,    &NDPluginDynamicROICentroidX);
    createParam(NDPluginDynamicROICentroidYString,         asynParamFloat64,    &NDPluginDynamicROICentroidY);
    createParam(NDPluginDynamicROISigmaXString,            asynParamFloat64,    &NDPluginDynamicROISigmaX);
    createParam(NDPluginDynamicROISigmaYString,            asynParamFloat64,    &NDPluginDynamicROISigmaY);
    createParam(NDPluginDynamicROISigmaXYString,           asynParamFloat64,    &NDPluginDynamicROISigmaXY);

    /* Profiles */
    createParam(NDPluginDynamicROIComputeProfilesString,   asynParamInt32,         &NDPluginDynamicROIComputeProfiles);
    createParam(NDPluginDynamicROIProfileSizeXString,      asynParamInt32,         &NDPluginDynamicROIProfileSizeX);
    createParam(NDPluginDynamicROIProfileSizeYString,      asynParamInt32,         &NDPluginDynamicROIProfileSizeY);
    createParam(NDPluginDynamicROICursorXString,           asynParamInt32,         &NDPluginDynamicROICursorX);
    createParam(NDPluginDynamicROICursorYString,           asynParamInt32,         &NDPluginDynamicROICursorY);
    createParam(NDPluginDynamicROIProfileAverageXString,   asynParamFloat64Array,  &NDPluginDynamicROIProfileAverageX);
    createParam(NDPluginDynamicROIProfileAverageYString,   asynParamFloat64Array,  &NDPluginDynamicROIProfileAverageY);
    createParam(NDPluginDynamicROIProfileThresholdXString, asynParamFloat64Array,  &NDPluginDynamicROIProfileThresholdX);
    createParam(NDPluginDynamicROIProfileThresholdYString, asynParamFloat64Array,  &NDPluginDynamicROIProfileThresholdY);
    createParam(NDPluginDynamicROIProfileCentroidXString,  asynParamFloat64Array,  &NDPluginDynamicROIProfileCentroidX);
    createParam(NDPluginDynamicROIProfileCentroidYString,  asynParamFloat64Array,  &NDPluginDynamicROIProfileCentroidY);
    createParam(NDPluginDynamicROIProfileCursorXString,    asynParamFloat64Array,  &NDPluginDynamicROIProfileCursorX);
    createParam(NDPluginDynamicROIProfileCursorYString,    asynParamFloat64Array,  &NDPluginDynamicROIProfileCursorY);

    /* ROI definition */
    createParam(NDPluginDynamicROIDim0MinString,           asynParamInt32, &NDPluginDynamicROIDim0Min);
    createParam(NDPluginDynamicROIDim0SizeString,          asynParamInt32, &NDPluginDynamicROIDim0Size);
    createParam(NDPluginDynamicROIDim0MaxSizeString,       asynParamInt32, &NDPluginDynamicROIDim0MaxSize);
    createParam(NDPluginDynamicROIDim1MinString,           asynParamInt32, &NDPluginDynamicROIDim1Min);
    createParam(NDPluginDynamicROIDim1SizeString,          asynParamInt32, &NDPluginDynamicROIDim1Size);
    createParam(NDPluginDynamicROIDim1MaxSizeString,       asynParamInt32, &NDPluginDynamicROIDim1MaxSize);
    createParam(NDPluginDynamicROIDataTypeString,          asynParamInt32, &NDPluginDynamicROIDataType);
    createParam(NDPluginDynamicROIDim0EnableString,        asynParamInt32, &NDPluginDynamicROIDim0Enable);
    createParam(NDPluginDynamicROIDim1EnableString,        asynParamInt32, &NDPluginDynamicROIDim1Enable);

    /* Set the plugin type string */
    setStringParam(NDPluginDriverPluginType, "NDPluginDynamicROI");

    /* Try to connect to the array port */
    connectToArrayPort();
}

/** Configuration command */
extern "C" int NDDynamicROIConfigure(const char *portName, int queueSize, int blockingCallbacks,
                                 const char *NDArrayPort, int NDArrayAddr,
                                 int maxBuffers, size_t maxMemory,
                                 int priority, int stackSize, int maxThreads)
{
    NDPluginDynamicROI *pPlugin = new NDPluginDynamicROI(portName, queueSize, blockingCallbacks, NDArrayPort, NDArrayAddr,
                                              maxBuffers, maxMemory, priority, stackSize, maxThreads);
    return pPlugin->start();
}

/* EPICS iocsh shell commands */
static const iocshArg initArg0 = { "portName",iocshArgString};
static const iocshArg initArg1 = { "frame queue size",iocshArgInt};
static const iocshArg initArg2 = { "blocking callbacks",iocshArgInt};
static const iocshArg initArg3 = { "NDArrayPort",iocshArgString};
static const iocshArg initArg4 = { "NDArrayAddr",iocshArgInt};
static const iocshArg initArg5 = { "maxBuffers",iocshArgInt};
static const iocshArg initArg6 = { "maxMemory",iocshArgInt};
static const iocshArg initArg7 = { "priority",iocshArgInt};
static const iocshArg initArg8 = { "stackSize",iocshArgInt};
static const iocshArg initArg9 = { "maxThreads",iocshArgInt};
static const iocshArg * const initArgs[] = {&initArg0,
                                            &initArg1,
                                            &initArg2,
                                            &initArg3,
                                            &initArg4,
                                            &initArg5,
                                            &initArg6,
                                            &initArg7,
                                            &initArg8,
                                            &initArg9};
static const iocshFuncDef initFuncDef = {"NDDynamicROIConfigure",10,initArgs};
static void initCallFunc(const iocshArgBuf *args)
{
    NDDynamicROIConfigure(args[0].sval, args[1].ival, args[2].ival,
                     args[3].sval, args[4].ival, args[5].ival,
                     args[6].ival, args[7].ival, args[8].ival,
                     args[9].ival);
}

extern "C" void NDDynamicROIRegister(void)
{
    iocshRegister(&initFuncDef,initCallFunc);
}

extern "C" {
epicsExportRegistrar(NDDynamicROIRegister);
}
