/*
 *  Wrapper.c
 *  mpsLinkProcessor
 *
 *  Created by Stephen Norum on 11/20/07.
 *  Copyright 2007 Stanford Linear Accelerator Center. All rights reserved.
 *
 */

#include <stdio.h>
#include <string.h>

#include <errlog.h>
#include <epicsTime.h>
#include <epicsMutex.h>
#include <epicsThread.h>
#include <epicsMessageQueue.h>
#include <cantProceed.h>

#include "MPS2007Common.h"
#include "AlgorithmHeader.h"
#include "AlgorithmWrapper.h"
#include "Mitigation.h"
#include "MachineRatesBuffer.h"
#include "MachineStateBuffer.h"
#include "MachineStateNameAndIndexMapping.h"
#include "MPSFaultNumbers.h"
#include "Macros.h"

#define OBJECT_VERSION 1


/* Extern Variables */
extern epicsMutexId algorithmListMutex;
extern ELLLIST      algorithmList;


/* List Element */
static algorithmData ad;

/* Prototype */
extern "C"
{
    int  ALGORITHM_FUNCTION_NAME  (void *arg);
    void ALGORITHM_FUNCTION_INIT  ();
    void ALGORITHM_FUNCTION_FINAL ();
}


int ALGORITHM_FUNCTION_NAME (void *arg)
{
    machineStateBuffers *buffers;
    
    char *deviceStateBuffer;
    char *bypassValueBuffer;
    char *bypassActiveBuffer;
    
    buffers = (machineStateBuffers *) arg;
    
    deviceStateBuffer  = buffers->deviceState;
    bypassValueBuffer  = buffers->bypassValue;
    bypassActiveBuffer = buffers->bypassActive;
    
    #include "Algorithm.h"
    
    /* Leave a blank line above incase Algorithm.h does not end with a blank line. */

    return SUCCESS;
}


static int addSelfToAlgorithmList()
{
    int err;
    
    if (strlen(ALGORITHM_REVISION_STRING) > MPSAlgorithmRevisionStringMaxLength)
    {
        /* Can't use this object data.  Unload the object*/
        errlogPrintf("Error: addSelfToAlgorithmList cannot use revision name over %d characters.", MPSAlgorithmRevisionStringMaxLength);
        return ERROR;
    }
        
    /* Initialize the element */
    ad.objectVersion      = OBJECT_VERSION;
    ad.year               = ALGORITHM_YEAR;
    ad.month              = ALGORITHM_MONTH;
    ad.day                = ALGORITHM_DAY;
    ad.revision           = ALGORITHM_REVISION_STRING;
    ad.function           = ALGORITHM_FUNCTION_NAME;
    ad.functionName       = ALGORITHM_FUNCTION_NAME_STRING;
    ad.mpsDatabaseVersion = MPS_DATABASE_VERSION_STRING;
    
    ad.canUnload     = TRUE;

    ad.compileDate   = __DATE__;
    ad.compileTime   = __TIME__;

    /* Try to add the algorithm to the list */
    err = addAlgorithmToList(&ad);
    
    return err;
}




/****************************************************************************************
 * C initializer and finalizer for cexpsh
 ***************************************************************************************/

#ifndef __cplusplus
void _cexpModuleInitialize (void *module_handle)
{
    epicsInt32 err;

    err = addSelfToAlgorithmList();
    
    errlogPrintf("Error: " ALGORITHM_FUNCTION_NAME_STRING " add self = %d.", err);
    
    if (err != SUCCESS)
    {
        /* Couldn't add this algorithm to the list.  Unload the object*/
        errlogPrintf("Error: " ALGORITHM_FUNCTION_NAME_STRING " initializer.  Couldn't add algorithm to list.  Unloading object.");
        #warning need to unload the algorithm here
    }
}



int _cexpModuleFinalize (void *module_handle)
{
    int err;

    /*
     * Return a non-zero value to indicate that it is
     * illegal or impossible to unload this module.
     */

    epicsMutexLock(algorithmListMutex);
    if (ad.canUnload == TRUE)
    {
        err = 0;
    }
    else
    {
        err = removeAlgorithmFromList(&ad);
        if (err == SUCCESS)
        {
            err = 0;
        }
        else
        {
            errlogPrintf("ERROR: " ALGORITHM_FUNCTION_NAME_STRING " finalizer.  Couldn't remove algorithm from list.");
            err = 1;
        }
    }
    epicsMutexUnlock(algorithmListMutex);

    return err;
}
#endif





/****************************************************************************************
 * C++ constructor and destructor for non-cexpsh
 ***************************************************************************************/

#ifdef __cplusplus
class algorithmObject {
public:
    algorithmObject() { ALGORITHM_FUNCTION_INIT ();  }
   ~algorithmObject() { ALGORITHM_FUNCTION_FINAL (); }
};

static algorithmObject dummyAlgorithmObject;



void ALGORITHM_FUNCTION_INIT ()
{
    int err;

    err = addSelfToAlgorithmList();
    
    if (err != SUCCESS) {
        /* Couldn't add this algorithm to the list.  Should not use this object. */
        errlogPrintf("Error: " ALGORITHM_FUNCTION_NAME_STRING " initializer.  Couldn't add algorithm to list.  This object should not be used.");
    }
}



void ALGORITHM_FUNCTION_FINAL ()
{
    int err;

    /* Unloading the object with this method may cause problems. */
    epicsMutexLock(algorithmListMutex);
    if (ad.canUnload != TRUE)
    {
        err = removeAlgorithmFromList(&ad);

        if (err != SUCCESS) {
            errlogPrintf("ERROR: " ALGORITHM_FUNCTION_NAME_STRING " finalizer.  Couldn't remove algorithm from list.  MPS code is unstable.");
        }
    }
    epicsMutexUnlock(algorithmListMutex);
}

#endif

