program setGap
        option +d;
        option -c;
        option +r;


/** Program initialization **/
/* C includes and method prototypes */
%{
#include <epicsThread.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <sys/time.h>
#include <epicsString.h>
#include <epicsStdio.h>
#include <asynOctetSyncIO.h>

#define inputEos "\r"
#define outputEos " "
#define BUF_SIZE 200

static int writeCommand(SS_ID ssId, struct UserVar *pVar, char *command, char *stateName);
static int writeRead(SS_ID ssId, struct UserVar *pVar, char *command, char *reply, char *stateName);
static int getMotorMoving(SS_ID ssId, struct UserVar *pVar);
static int waitEpicsMotors(SS_ID ssId, struct UserVar *pVar);
static int getTimeStamp(SS_ID ssId, char *timeStampString);
static int logToIOCshell(SS_ID ssId, char *logMessage);
static int waitBrakesReleased(SS_ID ssId, struct UserVar *pVar);
static int queryBrakesReleased(SS_ID ssId, struct UserVar *pVar);
}%

/** SNL variables  **/
/* Configuration and communication */
char stringOut[200];
char stringIn[200];
char *asynPort;
char *pasynUser;
int initStatus = 0;
int numAxes = 4;
int movingLarger = 0;
/* Status for asyn operations */
int sg_status = 0;
int am_status = 0;
int brake_status = 0;

/* HXU strongback distances in mm */
/* distance beetween upstream end and downstream end */
double distEndToEnd = 3419.050;
/* distance between upstream end and upstream motor */
double distToUsMtr =  798.525;
/* distance between upstream end and downstream motor */
double distToDsMtr = 2620.525;
/* distance between upstream motor and downstream motor */
double distBtwnMtr = 1822.000;

/* Positions and new values */
double desiredGapTemp = 0;
double deadbandTemp = 0;
double desiredUsMotorPosition = 0;
double desiredDsMotorPosition = 0;
double usaMotorAmountToMove = 0;
double uswMotorAmountToMove = 0;
double dsaMotorAmountToMove = 0;
double dswMotorAmountToMove = 0;
double moveFraction = 0.9;
double deadband_hg = 0.0010;
double deadband_fg = 0.00025;

/* Full gap encoder feedback */
int fullGapEncCorrection = 0;
int fullGapCorrectionNeeded = 0;
double currentGapFromFullGapEncoders = 0 ;
double currentTaperFromFullGapEncoders = 0;
double userDesiredGap = 0;
double userDesiredTaper = 0;
double usError = 0;
double dsError = 0;
double deltaError = 0;

double usaPos = 0;
double uswPos = 0;
double dsaPos = 0;
double dswPos = 0;
int usaPos_raw = 0;
int uswPos_raw = 0;
int dsaPos_raw = 0;
int dswPos_raw = 0;
int moveVelo_raw = 0;
int acclDccl_raw = 0;

int sampleRate = 0;
double scalingFactorVelo = 0;
double scalingFactorAD = 0;
double deadband = 0.010;

/* Setpoint PVs */
double desiredGap;        assign desiredGap   to "{DEV}:GapDes";
double desiredTaper;      assign desiredTaper to "{DEV}:TaperDes";
double desiredUsGap;      assign desiredUsGap to "{DEV}:US:GapDes";
double desiredDsGap;      assign desiredDsGap to "{DEV}:DS:GapDes";
/* Move precision and retry */
double deadband_mm;       assign deadband_mm to "{DEV}:DeadbandHgEnc";
double deadband_enc;      assign deadband_enc to "{DEV}:DeadbandFgEnc";
double moveFrac;          assign moveFrac to "{DEV}:MoveFraction";
double finalMoveFrac;     assign finalMoveFrac to "{DEV}:FinalMoveFraction";
double finalMoveRange;    assign finalMoveRange to "{DEV}:FinalMoveRange";
double moveVelo;          assign moveVelo to "{DEV}:MotorsVelocity";
double acclDccl;          assign acclDccl to "{DEV}:MotorsAccl";
int singleApproach;       assign singleApproach to "{DEV}:SingleApproach";      monitor singleApproach;
int overcurrents;         assign overcurrents to "{DEV}:Overcurrents";
int retry;                assign retry to "{DEV}:Retries";
int retryMax;             assign retryMax to "{DEV}:MaxRetries";
double clRegionOfIntr;    assign clRegionOfIntr to "{DEV}:CLRegionOfInterest";  monitor clRegionOfIntr;
int clEncSelection;       assign clEncSelection to "{DEV}:CloseLoopEncoder";    monitor clEncSelection;

/* Position readback PVs */
double actualGap;         assign actualGap to "{DEV}:GapAct";                       monitor actualGap;
double actualTaper;       assign actualTaper to "{DEV}:HG:TaperAct";                monitor actualTaper;
double calcUsGap;         assign calcUsGap to "{DEV}:US:GapAct";                    monitor calcUsGap;
double calcDsGap;         assign calcDsGap to "{DEV}:DS:GapAct";                    monitor calcDsGap;
double calcAisleTaper;    assign calcAisleTaper to "{DEV}:AisleTaper";          monitor calcAisleTaper;
double calcWallTaper;     assign calcWallTaper to "{DEV}:WallTaper";            monitor calcWallTaper;
double calcUsSymmetry;    assign calcUsSymmetry to "{DEV}:US:Symmetry";          monitor calcUsSymmetry;
double calcDsSymmetry;    assign calcDsSymmetry to "{DEV}:DS:Symmetry";          monitor calcDsSymmetry;

/* Hardware position readback PVs */
double usFullGapEncoder;  assign usFullGapEncoder  to "{SDEV}:US:EncRbck";     monitor usFullGapEncoder; 
double dsFullGapEncoder;  assign dsFullGapEncoder  to "{SDEV}:DS:EncRbck";     monitor dsFullGapEncoder; 
/* double usFullGapEncoder;  assign usFullGapEncoder  to "{SDEV}:USFullGapEnc_S";     monitor usFullGapEncoder;*/ 
/* double dsFullGapEncoder;  assign dsFullGapEncoder  to "{SDEV}:DSFullGapEnc_S";     monitor dsFullGapEncoder;*/
double usaHalfGapEncoder; assign usaHalfGapEncoder to "{DEV}:USPOSX:EncRbck"; monitor usaHalfGapEncoder;
double uswHalfGapEncoder; assign uswHalfGapEncoder to "{DEV}:USNEGX:EncRbck"; monitor uswHalfGapEncoder;
double dsaHalfGapEncoder; assign dsaHalfGapEncoder to "{DEV}:DSPOSX:EncRbck"; monitor dsaHalfGapEncoder;
double dswHalfGapEncoder; assign dswHalfGapEncoder to "{DEV}:DSNEGX:EncRbck"; monitor dswHalfGapEncoder;

/* Motor position setpoint */
double usaMotorVal;       assign usaMotorVal to "{DEV}:USPOSX:Motor.VAL";           monitor usaMotorVal;
double uswMotorVal;       assign uswMotorVal to "{DEV}:USNEGX:Motor.VAL";           monitor uswMotorVal;
double dsaMotorVal;       assign dsaMotorVal to "{DEV}:DSPOSX:Motor.VAL";           monitor dsaMotorVal;
double dswMotorVal;       assign dswMotorVal to "{DEV}:DSNEGX:Motor.VAL";           monitor dswMotorVal;
/* Motor position readback */
double usaMotorRbv;       assign usaMotorRbv to "{DEV}:USPOSX:Motor.RBV";           monitor usaMotorRbv;
double uswMotorRbv;       assign uswMotorRbv to "{DEV}:USNEGX:Motor.RBV";           monitor uswMotorRbv;
double dsaMotorRbv;       assign dsaMotorRbv to "{DEV}:DSPOSX:Motor.RBV";           monitor dsaMotorRbv;
double dswMotorRbv;       assign dswMotorRbv to "{DEV}:DSNEGX:Motor.RBV";           monitor dswMotorRbv;
/* Motor position calculated from encoder */
double usaMotorGap;       assign usaMotorGap to "{DEV}:USPOSX:MotorHalfGapAct";            monitor usaMotorGap;
double uswMotorGap;       assign uswMotorGap to "{DEV}:USNEGX:MotorHalfGapAct";            monitor uswMotorGap;
double dsaMotorGap;       assign dsaMotorGap to "{DEV}:DSPOSX:MotorHalfGapAct";            monitor dsaMotorGap;
double dswMotorGap;       assign dswMotorGap to "{DEV}:DSNEGX:MotorHalfGapAct";            monitor dswMotorGap;
double motorResolution;   assign motorResolution to "{DEV}:USPOSX:Motor.MRES";

/* HGVPU command and status PVs */
int startGapAdjustment;   assign startGapAdjustment to "{DEV}:Go";           monitor startGapAdjustment;
int stop;                 assign stop to "{DEV}:Stop";                          monitor stop;
int checkGap;             assign checkGap to "{DEV}:CheckGap";                  monitor checkGap;
int undulatorError;       assign undulatorError to "{DEV}:UndulatorError";      monitor undulatorError;
int calibMotors;          assign calibMotors to "{DEV}:CalibrateMotors.PROC";
int movingDirection;      assign movingDirection to "{DEV}:MotionDirection";
int deviceActive;         assign deviceActive to "{DEV}:DeviceActive";
string message1;          assign message1 to "{DEV}:IdControlMsg.VAL";
string message2;          assign message2 to "{DEV}:EmergencyMsg.VAL";


/* Debug and simulation PVs */
int debugLevel;           assign debugLevel to "{DEV}:DebugLevel.VAL";          monitor debugLevel;
int simMode;              assign simMode to "{DEV}:SimMode.VAL";                monitor simMode;
string setGapState;       assign setGapState to "{DEV}:SeqProgramState.VAL";


/* stateSet to change gap */
ss setGap
{
  /* Initialize state */
  state init {
    entry {
      pvGet(debugLevel,SYNC);
      if (debugLevel) logToIOCshell(ssId, "setGap:init: entry");

      sprintf(setGapState, "setGap:init");
      pvPut(setGapState, SYNC);
      sg_status = 0;
      /* Initialization of variables and PVs */
      /*initStatus = 0;*/
      stop = 0;
      pvPut(stop, SYNC);
      retry = 0;
      pvPut(retry, SYNC);
      overcurrents = 0;
      pvPut(overcurrents, SYNC);
      startGapAdjustment = 0;
      pvPut(startGapAdjustment, SYNC);
      deviceActive = 0;
      pvPut(deviceActive, SYNC);
      numAxes = 4;

      /* Connecting to ASYN port for motors */
      asynPort = macValueGet("PORT");
      %%pVar->sg_status = pasynOctetSyncIO->connect(pVar->asynPort, 0, (asynUser **)&pVar->pasynUser, NULL);
      if (sg_status != 0) {
        logToIOCshell(ssId, "trajectoryScan error in pasynOctetSyncIO->connect");
        printf("   sg_status=%d, port=%s\n", sg_status, asynPort);
      }

      /* Retrive sampling rate of the motor */
      sprintf(stringOut, "RSAMP:1");
      %%pVar->sg_status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn, pVar->setGapState);
      if (sg_status != 0)
        sampleRate = 8000;
      else
        sampleRate = atoi(stringIn);

      /* Set scaling factor for velocity and acceleration */
      scalingFactorVelo = 65536.0 / sampleRate;
      scalingFactorAD = scalingFactorVelo / sampleRate;

      if (initStatus == 0) initStatus = 1;
      if (debugLevel) logToIOCshell(ssId, "setGap:init: done; going to 'idle'");
    }

    /* Continue to idle state */
    when() {
    } state idle
  }

  /* Idle state and on change of EPICS PVs preform action */
  state idle {
    entry {
      if (debugLevel) logToIOCshell(ssId, "setGap:idle: entry");
      sprintf(setGapState, "setGap:idle");
      pvPut(setGapState, SYNC);
      /* Clear flags that indicate/start motion */
      startGapAdjustment = 0;
      pvPut(startGapAdjustment, SYNC);
      if (deviceActive < 2) {
        deviceActive = 0;
        pvPut(deviceActive, SYNC);
      }
      movingLarger = 0;
      fullGapEncCorrection = 0;
    }

    /* writeRead() or writeCommand() has failed in the transition leading to this state*/
    when(sg_status != 0) {
      printf(" setGap:idle ERROR: previous writeCommand()/writeRead() returned %d. Clearing the status and returning to idle.\n", sg_status);
      sg_status = 0;
    } state idle

    /* If stop is issued */
    when(stop == 1) {
      if (debugLevel) logToIOCshell(ssId, "setGap:idle: going to 'stop'");
    } state stop

    /* Device is in not safe state for operation, clear start flage and return to idle state */
    when((startGapAdjustment == 1) && ((undulatorError == 1) || (checkGap == 1))) {
      /* Report message on the screen */
      sprintf(message2,"Device not ready to move!");
      pvPut(message2,SYNC);
      /* Clear Flag */
      startGapAdjustment = 0;
      pvPut(startGapAdjustment,SYNC);
    } state idle

    /* When motors are commanded to Start and no errors reported from undulator */
    when((startGapAdjustment == 1) && (undulatorError == 0) && (checkGap == 0)) {

      /* Retrieve PV values */
      pvGet(desiredGap,SYNC);
      pvGet(desiredTaper,SYNC);
      userDesiredGap = desiredGap;
      userDesiredTaper = desiredTaper;
      pvGet(desiredUsGap,SYNC);
      pvGet(desiredDsGap,SYNC);
      pvGet(deadband_mm,SYNC);
      pvGet(deadband_enc,SYNC);
      // deadband is stored as micron, convert to millimeters first:
      deadband_mm = deadband_mm / 1000.;
      deadband_enc = deadband_enc / 1000.;
      pvGet(moveFrac,SYNC);
      pvGet(moveVelo,SYNC);
      pvGet(acclDccl,SYNC);
      pvGet(motorResolution,SYNC);
      pvGet(retryMax,SYNC);

      /* Assign the deadband for the full gap encoders*/
      deadband_fg = deadband_mm;

      /* Set half gap encoders deadband*/
      /* Only using half gap encoders*/
      if(clEncSelection == 0) {
          deadband_hg = deadband_mm;
          deadband_enc = (deadband_mm *1000.0);
          pvPut(deadband_enc, SYNC);
      }
      /* Unsing full gap encoders*/
      else {
          deadband_hg = deadband_enc;
      }	
      
      if (debugLevel) printf("setGap:dle: deadband_mm = %f, deadband_enc = %f, deadband_hg = %f, deadband_fg = %f\n", deadband_mm, deadband_enc, deadband_hg, deadband_fg);

      /* Write start message to the PV */
      sprintf(message1, "Device Started");
      pvPut(message1,SYNC);
      sprintf(message2, " ");
      pvPut(message2,SYNC);

      /* Calculate direction of the move */
      if (desiredGap > actualGap)
        movingDirection = 1;
      else
        movingDirection = 0;
      pvPut(movingDirection, SYNC);

      /* Clear retries and Go flag */
      retry = 0;
      pvPut(retry, SYNC);
      startGapAdjustment = 0;
      pvPut(startGapAdjustment, SYNC);
      deviceActive = 1;
      pvPut(deviceActive, SYNC);

      /* If single approach and opening gap */
      if( (desiredGap > actualGap) && (singleApproach == 1) ) {
        /* Store desired gap and deadband */
        desiredGapTemp = desiredGap;
        deadbandTemp = deadband_mm;
        /* Enlarge desired gap and deadband for single approach inital move */
        desiredGap = desiredGap + 1;
        deadband_mm = 0.0005;
        movingLarger = 1;
      }
      if (debugLevel) logToIOCshell(ssId, "setGap:idle: going to 'calcMove'");
    } state calcMove
  }

  /* State for calculating new motor positions */
  state calcMove {
    entry {
      if (debugLevel) logToIOCshell(ssId, "setGap:calcMove: entry'");
      sprintf(setGapState, "setGap:calcMove");
      pvPut(setGapState, SYNC);
    }

    /* If stop is issued or writeCommand()/writeRead() has failed in the transition leading to this state */
    when( (stop == 1) || (sg_status != 0) ) {
      if (sg_status != 0)
        printf(" setGap:calcMove ERROR: previous writeRead() returned %d. Going to stop.\n", sg_status);
    } state stop

    /* Disable retry checking for time based gap setting */
    when(retry >= retryMax) {
      if (debugLevel) printf("setGap:calcMove: retry >= retryMax %d >= %d\n", retry, retryMax);
    } state moveComplete

    /* When in single approach and gap above modified desired gap */
    when( (movingLarger == 1) && (actualGap > (desiredGap - 0.5))) {
      if (debugLevel) logToIOCshell(ssId, "setGap:calcMove: single approach, above desired gap");
    } state moveComplete

    /* Calculate new positions */
    when() {
      /* Calibrate motor positions with linear encoder readback */
      calibMotors = 1;
      pvPut(calibMotors,SYNC);

      /* Fix the desired position for difference between desired gap and full gap encoders */
      if ( fullGapEncCorrection && (movingLarger == 0) ) {
        if (debugLevel) 
          printf("   ** Performing full gap encoder correction **\n");
          printf(" US encoder: %f , DS encoder: %f\n", usFullGapEncoder, dsFullGapEncoder);
        usError = (desiredUsGap-usFullGapEncoder)/2.0;
        dsError = (desiredDsGap-dsFullGapEncoder)/2.0; 
        deltaError = dsError - usError;

        usaMotorAmountToMove = usError + (distToUsMtr/distEndToEnd)*deltaError;
        uswMotorAmountToMove = usError + (distToUsMtr/distEndToEnd)*deltaError;
        dsaMotorAmountToMove = usError + (distToDsMtr/distEndToEnd)*deltaError;
        dswMotorAmountToMove = usError + (distToDsMtr/distEndToEnd)*deltaError;
       
        printf("usError %f dsError %f deltaError %f\n", usError, dsError, deltaError);
        printf("usaMotorAmountToMove %f  uswMotorAmountToMove %f \n", usaMotorAmountToMove, uswMotorAmountToMove);
        printf("dsaMotorAmountToMove %f  dswMotorAmountToMove %f \n", dsaMotorAmountToMove, dswMotorAmountToMove);
 
	/*usaMotorAmountToMove = (distToDsMtr/distEndToEnd)*usError - (distToUsMtr/distEndToEnd)*dsError;
        uswMotorAmountToMove = (distToDsMtr/distEndToEnd)*usError - (distToUsMtr/distEndToEnd)*dsError;
        dsaMotorAmountToMove = (distToDsMtr/distEndToEnd)*dsError - (distToUsMtr/distEndToEnd)*usError;
        dswMotorAmountToMove = (distToDsMtr/distEndToEnd)*dsError - (distToUsMtr/distEndToEnd)*usError;*/
      }
      else {
        if (debugLevel) 
          printf("   ** Performing half gap encoder correction **\n");
        
	/* Calculating new motor positions based on distances between strongback end and motor position*/
        desiredUsMotorPosition = (desiredGap/2.0) + (distToUsMtr/distEndToEnd)*(desiredTaper/2.0);
        desiredDsMotorPosition = (desiredGap/2.0) + (distToDsMtr/distEndToEnd)*(desiredTaper/2.0);
  
        usaMotorAmountToMove = desiredUsMotorPosition - usaMotorGap;
        uswMotorAmountToMove = desiredUsMotorPosition - uswMotorGap;
        dsaMotorAmountToMove = desiredDsMotorPosition - dsaMotorGap;
        dswMotorAmountToMove = desiredDsMotorPosition - dswMotorGap;
      }

      /* Calculate factor for retries */
      if ( fabs(actualGap - desiredGap ) < finalMoveRange )
        /* If small adjustment, move motor to end point */
        moveFraction = finalMoveFrac;
      else
        /* Otherwis do fraction of the move */
        moveFraction = moveFrac;

      /* Calculate new motor positions */
      usaPos = usaMotorRbv + moveFraction * usaMotorAmountToMove;
      uswPos = uswMotorRbv + moveFraction * uswMotorAmountToMove;
      dsaPos = dsaMotorRbv + moveFraction * dsaMotorAmountToMove;
      dswPos = dswMotorRbv + moveFraction * dswMotorAmountToMove;

      /* Scale new positions to raw value and push to motor */
      usaPos_raw = (int) (usaPos / motorResolution);
      uswPos_raw = (int) (uswPos / motorResolution);
      dsaPos_raw = (int) (dsaPos / motorResolution);
      dswPos_raw = (int) (dswPos / motorResolution);
      moveVelo_raw = (int) ((moveVelo/motorResolution) * scalingFactorVelo);
      //TODO: fix acceleration
      acclDccl_raw = (int) (((moveVelo/motorResolution) / acclDccl) * (scalingFactorAD*100));
      
      if (debugLevel) {
        printf("    calcMove: desiredGap = %f, desiredTaper = %f'\n", desiredGap, desiredTaper);
        printf("    calcMove: currentGap = %f, currentTaper = %f'\n", actualGap, actualTaper);
        printf("    calcMove: moveFraction = %f'\n", moveFraction);
        printf("    calcMove: retry = %d'\n", retry);
        printf("    calcMove: usError = %.6f  dsError = %.6f'\n", usError, dsError);
        printf("    calcMove: uswPos = %f (%d) Delta to target: %f\n", uswPos, uswPos_raw, uswMotorAmountToMove);
        printf("    calcMove: dswPos = %f (%d) Delta to target: %f\n", dswPos, dswPos_raw, dswMotorAmountToMove);
        printf("    calcMove: dsaPos = %f (%d) Delta to target: %f\n", dsaPos, dsaPos_raw, dsaMotorAmountToMove);
        printf("    calcMove: usaPos = %f (%d) Delta to target: %f\n", usaPos, usaPos_raw, usaMotorAmountToMove);
        printf("    calcMove: moveVelo = %f (%d)\n", moveVelo, moveVelo_raw);
        printf("    calcMove: acclDccl = %f (%d)\n", acclDccl, acclDccl_raw);
      }

    } state checkMove
  }

  state checkMove {
    entry {
      if (debugLevel){
        logToIOCshell(ssId, "setGap:checkMove: entry");
      }
      sprintf(setGapState, "setGap:checkMove");
      pvPut(setGapState, SYNC);
      fullGapCorrectionNeeded = ((clEncSelection == 1) && (desiredGap < clRegionOfIntr) &&
                                 (retry < retryMax) &&
                                 (fabs(desiredUsGap-usFullGapEncoder)>(2.0*deadband_fg) || 
                                  fabs(desiredDsGap-dsFullGapEncoder)>(2.0*deadband_fg) ) );

      /* set deadband depending on type of encoder used */
      /* If closing the loop on full gap encoders use smaller deadband */
      /* if(fullGapCorrectionNeeded && fullGapEncCorrection) {*/
      if(fullGapEncCorrection) {
          deadband = deadband_fg;
      } 
      /* if closing the gap on half gap encoders use bigger deadband */
      else {
          deadband = deadband_hg;
      }

      if (debugLevel) 
        printf("    checkMove: fullGapCorrectionNeeded = %d deadband = %f fullGapEncCorrection = %d\n", fullGapCorrectionNeeded, deadband, fullGapEncCorrection);
    }

    /* when all adjustments are below deadband (adaptive) mark motion as complete */
    when( (fabs(usaMotorAmountToMove) < deadband) && 
          (fabs(uswMotorAmountToMove) < deadband) &&
          (fabs(dsaMotorAmountToMove) < deadband) && 
          (fabs(dswMotorAmountToMove) < deadband) ) {
      if (debugLevel) 
        logToIOCshell(ssId, "setGap:checkMove: Move unnecessary; skipping");
      // epicsThreadSleep(0.5);
    } state moveComplete

    when () {
      /* Create a string to send to controller to start motor move */
      sprintf(stringOut, "iii:1=%d", uswPos_raw);
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      sprintf(stringOut, "jjj:1=%d", dswPos_raw);
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      sprintf(stringOut, "kkk:1=%d", dsaPos_raw);
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      sprintf(stringOut, "lll:1=%d", usaPos_raw);
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      sprintf(stringOut, "vvv:1=%d", moveVelo_raw);
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      sprintf(stringOut, "aaa:1=%d", acclDccl_raw);
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);

      /* Enable motors and disable breaks */
      sprintf(stringOut, "BRKRLS:0");
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);

      %%pVar->brake_status = waitBrakesReleased(ssId, pVar);
     
      } state move
  }

  /* State that starts the move */
  state move {
    entry {
      if (debugLevel){
        logToIOCshell(ssId, "setGap:move: entry");
      }
      sprintf(setGapState, "setGap:move");
      pvPut(setGapState, SYNC);
    }

    /* If stop is issued or writeCommand()/writeRead() has failed in the transition leading to this state */
    when( (stop == 1) || (sg_status != 0) || (brake_status == 1)) {
      if (sg_status != 0)
        printf(" setGap:move ERROR: previous write returned %d. Going to stop.\n", sg_status);
    } state stop

    /* Send command to start motion */
    when( delay(0.2) ) {
      if (debugLevel) logToIOCshell(ssId, "setGap:move: Waiting for any previous motion to complete");
      /* Wait if any of the motors is moving */
      %%pVar->sg_status = waitEpicsMotors(ssId, pVar);
      if (debugLevel) logToIOCshell(ssId, "setGap:move: Wait complete");
      printf("waitEpicsMotors status: %d\n", sg_status);
      
      /* Send comand to start move */
       sprintf(stringOut, "GOSUB(1)");
       %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);

    } state moving
  }

  /* State while motors are moving */
  state moving {
    entry {
      if (debugLevel) logToIOCshell(ssId, "setGap:moving: entry");
      sprintf(setGapState, "setGap:moving");
      pvPut(setGapState, SYNC);
    }

    /* If stop is issued or writeCommand()/writeRead() has failed in the transition leading to this state */
    when( (stop == 1) || (sg_status != 0) ) {
      if (sg_status != 0)
        printf(" setGap:move ERROR: previous writeRead() returned %d. Going to stop.\n", sg_status);
    } state stop

    /* When moving */
    when(delay(0.2)) {
      /*Wait while motors are moving */
      %%pVar->sg_status = waitEpicsMotors(ssId, pVar);
      printf("moving: waitEpicsMotors status: %d\n", sg_status);
      /* If something went wrong stop*/
      if(sg_status == 2) {
         stop = 1;
         sprintf(message2,"Over-current fault!!");
         pvPut(message2,SYNC);
         /* Signal failure */
         deviceActive = 2;
         pvPut(deviceActive, SYNC);
         /* Increase count of overcurrents */
         overcurrents = overcurrents + 1;
         pvPut(overcurrents, SYNC);
      }
      else {
         /* When move done, increase number of retrys */
         retry = retry + 1;
         pvPut(retry, SYNC);
      }
    } state calcMove
  }

  /* State when motors finish move */
  state moveComplete {
    entry {
      if (debugLevel) logToIOCshell(ssId, "setGap:moveComplete: entry'");
      sprintf(setGapState, "setGap:moveComplete");
      pvPut(setGapState, SYNC);
    }

    /* If stop is issued or writeCommand()/writeRead() has failed in the transition leading to this state */
    when( (stop == 1) || (sg_status != 0) ) {
      if (sg_status != 0)
        printf(" setGap:move ERROR: previous writeRead() returned %d. Going to stop.\n", sg_status);
    } state stop

    /* When in single approach */
    when( movingLarger == 1) {
      /* Restore original values */
      movingLarger = 0;
      desiredGap = desiredGapTemp;
      deadband_mm = deadbandTemp;
    } state calcMove

    /* If closing loop on full gap encoder,
     * desired gap is within region of interest for full gap closed loop corrections,
     * and US and DS gap encoders differ from desired points */

    /* This is the check that keeps closing the loop on full gap encoders active: 
     * diff is still above min deadband but motion was marked as complete */

    when( (clEncSelection == 1) && (desiredGap < clRegionOfIntr) &&
          (retry < retryMax) && (fullGapEncCorrection == 0) &&
          (   fabs(desiredUsGap-usFullGapEncoder)>(2.0*deadband_fg) 
          ||  fabs(desiredDsGap-dsFullGapEncoder)>(2.0*deadband_fg) ) ) {
      if (debugLevel)
        logToIOCshell(ssId, "setGap: moveComplete: FullGapEncoder closedLoop: adjusting desired position");
        /* Limit max retries with full gap encoder */
        /* retryMax = retry + 4; */
        /* Correction for FullGap Closed loop flag*/
        fullGapEncCorrection = 1;
    } state calcMove

    /* On complete move */
    when() {
      /* Issue a global stop */
      sprintf(stringOut, "S:0");
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      if ( sg_status != 0 ) {
        sprintf(stringOut, "S:0");
        %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      }
      /* Engage brakes on all motors */
      sprintf(stringOut, "BRKENG:0");
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      /* Turn Off motor current */
      sprintf(stringOut, "OFF:0");
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);

      /* Calibrate motors at final position */
      calibMotors = 1;
      pvPut(calibMotors, SYNC);

      if (retry >= retryMax) {
        deviceActive = 2;
        pvPut(deviceActive,SYNC);
        sprintf(message1, "Max Retries Failed");
        pvPut(message1);

      }
      else {
        /* Write message to a PV */
        sprintf(message1, "Device At Destination");
        pvPut(message1);
      }
     
     /* Print encoders readouts when motion is complete	 */
     if (debugLevel){
        printf("    moveComplete: usFullGapEncoder = %f mm, dsFullGapEncoder = %f mm\n", usFullGapEncoder, dsFullGapEncoder);
        printf("    moveComplete: usaHalfGapEncoder = %f mm, uswHalfGapEncoder = %f mm\n", usaHalfGapEncoder, uswHalfGapEncoder);
        printf("    moveComplete: dsaHalfGapEncoder = %f mm, dswHalfGapEncoder = %f mm\n", dsaHalfGapEncoder, dswHalfGapEncoder);
    }
    } state idle
  }

  /* Stop state */
  state stop {
    entry{
      if (debugLevel) logToIOCshell(ssId, "setGap:stop: entry'");
      sprintf(setGapState, "setGap:stop");
      pvPut(setGapState, SYNC);
    }

    /* On STOP flag */
    when() {

      if (sg_status > 0)
        logToIOCshell(ssId, "Trying to stop the motors after writeRead error! Then transition into idle");

      /* Send out an Abort all axes command */
      sprintf(stringOut, "S:0");
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      sprintf(stringOut, "BRKENG:0");
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);
      /* Turn Off motor current */
      sprintf(stringOut, "OFF:0");
      %%pVar->sg_status = writeCommand(ssId, pVar, pVar->stringOut, pVar->setGapState);

      /* Raise virtual axis done moving flag */
      /*deviceActive = 2;
      pvPut(deviceActive, SYNC);
      */
      /* Clear stop flag */
      stop = 0;
      pvPut(stop, SYNC);

      sprintf(message1, "Device Stopped");
      pvPut(message1,SYNC);
    } state idle
  }
}


%{

/* Write operation through asyn port */
static int writeCommand(SS_ID ssId, struct UserVar *pVar, char *command, char *stateName)
{
  asynStatus status=0;
  size_t nwrite;
  char output_buf[BUF_SIZE];

  sprintf(output_buf, "%s ", command);

  if (!(pVar->simMode)) {
    status = pasynOctetSyncIO->write((asynUser *)pVar->pasynUser, output_buf,
             strlen(output_buf), 2.0, &nwrite);
    if (status) printf("writeCommand called from %s: pasynOctetSyncIO->write returned %d\n", stateName, status);
 }
  if (pVar->simMode || pVar->debugLevel) {
    printf("    writeCommand:command='%s'\n", output_buf);
  }

  return(status);
}
/* WriteRead operation through asyn port */
static int writeRead(SS_ID ssId, struct UserVar *pVar, char *command, char *reply, char *stateName)
{
  asynStatus status=0;
  size_t nwrite, nread;
  int eomReason;
  char output_buf[BUF_SIZE];

  sprintf(output_buf, "%s ", command);

  if (!(pVar->simMode)) {
    status = pasynOctetSyncIO->writeRead((asynUser *)pVar->pasynUser, output_buf,
             strlen(output_buf), reply, BUF_SIZE, 2.0, &nwrite, &nread, &eomReason);
    if (status) printf("writeRead called from %s: pasynOctetSyncIO->writeRead returned %d\n", stateName, status);
 }
  if (pVar->simMode || pVar->debugLevel) {
    printf("    writeRead:command='%s', reply='%s'\n", output_buf, reply);
  }

  return(status);
}

/* Check if motors are moving */
static int getMotorMoving(SS_ID ssId, struct UserVar *pVar)
{
  char inputBuff[BUF_SIZE], outputBuff[BUF_SIZE];
  size_t nwrite, nread;
  int eomReason;
  int move_active = 0;
  int over_current = 0;
  int count, status, can_addr;

  #define MOVING 0x4
  #define OVERCURRENT 0x10

  for (can_addr=1, count=0; can_addr <= pVar->numAxes; can_addr++) {
    /* If Stop is issued while in for loop */
    if ( pVar->stop == 1 )
      return 0;

    /* Create command that reads motor status word */
    sprintf(outputBuff, "RW(0):%d", can_addr);
    /* Send command to the controller */
    status = pasynOctetSyncIO->writeRead((asynUser *)pVar->pasynUser, outputBuff,
             strlen(outputBuff), inputBuff, BUF_SIZE, 1.0, &nwrite, &nread, &eomReason);

    if (status)
      printf("getMotorMoving: pasynOctetSyncIO->writeRead returned %d\n", status);
    
    /* Parse return of the command */
    move_active |= (atoi(inputBuff) & MOVING) == MOVING;
   
    
    /*parse if overcurrent fault*/
    over_current = (atoi(inputBuff) & OVERCURRENT) == OVERCURRENT;
    if(pVar->debugLevel){
      printf("getMotorMoving: can_addr %d inputBuff %s move_active %d over_current %d\n", can_addr, inputBuff, move_active, over_current);
    }
    if(over_current == 1) {
      /*return error exit code*/
      return 2;
    }

    /* If any motor is moving return 1  */
    if (move_active)
      return 1;
    /* Otherwise increase the count and continue */
    else {
      count++;
      if (count>3) break;
    }
  }

  return 0;
}

/* Wait while motors are moving */
static int waitEpicsMotors(SS_ID ssId, struct UserVar *pVar)
{
  if(pVar->debugLevel)
    logToIOCshell(ssId, "waitEpicsMotors");
  /* Read status of motors, if they are moving */
  int rv = 0;
  rv = getMotorMoving(ssId, pVar);
  /* Try one more time if motors are not moving */
  if(rv == 0) {
    epicsThreadSleep((1/10.0));
    rv = getMotorMoving(ssId, pVar);
  }
  epicsThreadSleep((1/10.0));
  /*while (getMotorMoving(ssId, pVar)) {*/
  while (rv == 1) {
    epicsThreadSleep((1/10.0));
    rv = getMotorMoving(ssId, pVar);
    printf("waitEpicsMotors %d \n", rv);
  }

 return rv;
}

static int queryBrakesReleased(SS_ID ssId, struct UserVar *pVar)
{
  char inputBuff[BUF_SIZE], outputBuff[BUF_SIZE];
  size_t nwrite, nread;
  int eomReason;
  int brake_engaged = 0;
  int status, can_addr;

  #define BRAKE_ENGAGED 0x1000

  for (can_addr=1; can_addr <= pVar->numAxes; can_addr++) {
    /* If Stop is issued while in for loop */
    if ( pVar->stop == 1 )
      return 0;

    /* Create command that reads motor status word */
    sprintf(outputBuff, "RW(3):%d", can_addr);
    /* Send command to the controller */
    status = pasynOctetSyncIO->writeRead((asynUser *)pVar->pasynUser, outputBuff,
             strlen(outputBuff), inputBuff, BUF_SIZE, 1.0, &nwrite, &nread, &eomReason);

    /* Parse return of the command */
    brake_engaged = ((atoi(inputBuff) & BRAKE_ENGAGED) == BRAKE_ENGAGED);

    if (pVar->debugLevel) {
      if (status)
        printf("    checkBrakesReleased: pasynOctetSyncIO->writeRead returned %d\n", status);
      printf("    checkBrakesReleased: '%s'=>'%s' brake_engaged=%d\n", 
             outputBuff, inputBuff, brake_engaged);
    }

    /* If any motor has a brake engaged, return immediately */
    if (brake_engaged)
      return 1;
  }

  return 0;
}

static int waitBrakesReleased(SS_ID ssId, struct UserVar *pVar)
{
  if(pVar->debugLevel)
    logToIOCshell(ssId, "waitBrakesReleased");
 
  /* Read status of motors, if they are moving */
  int failed_count=0;
  while (queryBrakesReleased(ssId, pVar)) {
    failed_count++;
    if (failed_count > 5) {
      printf("here\n");
      return 1;
    }
    writeCommand(ssId, pVar, "BRKRLS:0", "waitBrakesReleased");
    /* wait a little */
    epicsThreadSleep((1/10.0));
  }
    
  /* Even if the brakes are released, wait a little before returning */
  int counter = 0;
  printf("BRAKES RELEASE WAIT counter %d\n", counter);
  epicsThreadSleep((1/2.0));
  printf("BRAKES RELEASE WAIT done sleeping\n");
  return 0;
}

/* Create a timestamp with current time */

static int getTimeStamp(SS_ID ssId, char *timeStampString)
{
  struct timeval preciseCurrentTime;
  time_t currentTime_sec;
  struct tm *currentTime;
  char tmp_buff[32];
  size_t size;

  gettimeofday(&preciseCurrentTime, NULL);
  currentTime_sec = preciseCurrentTime.tv_sec;
  currentTime = localtime(&currentTime_sec);
  size = strftime(tmp_buff, sizeof tmp_buff, "%Y-%m-%d_%H:%M:%S", currentTime);
  snprintf(timeStampString, (size + 8) , "%s.%06ld", tmp_buff, preciseCurrentTime.tv_usec);
  return(0);
}

static int logToIOCshell(SS_ID ssId, char *logMessage) {
  char timestamp[32];
  getTimeStamp(ssId, timestamp);
  printf("%s : %s\n",timestamp, logMessage);
  return(0);
}

}%

