/*=====================================================================*
 *  Module .............btdiag
 *  File ...............btdiag.c
 *  Author .............Traveler Hauptman
 *  Creation Date ......14 Oct 2005
 *                                                                      *
 *  ******************************************************************  *
 *                                                                      *
 *  NOTES:
 *
 *  REVISION HISTORY:
 *
 *  Adapted for prosthetic arm control application by 
 *  Meel Velliste and Sagi Perel
 *  July 2006
 *
 *  Added realtime BarrettHand control
 *  Meel Velliste
 *  December 2007
 *                                                                      *
 *======================================================================*/

/** \file btdiag.c
    \brief An interactive demo of wam capabilities.
 
    Read the code to see what you can do with it.
    
This program allows a user to test and interact with the teach and play
features of the WAM library.
 
The user can switch between cartesian space and joint space. The toggle 
variable is a pointer to the present btstatecontroller.
 
Note that if a trajectory is modified, you must call 's' scale trajectory on
it to properly establish the time values.
*/


#define DEBUG_HAND

/*==============================*
 * INCLUDES - System Files      *
 *==============================*/
#include <syslog.h>
#include <signal.h>
#include <pthread.h>
#include <errno.h>
#include <curses.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/io.h>
#include <sys/ioctl.h>

#include <rtai_lxrt.h>
#include <rtai_sem.h>

#include "../common_defs.h"
#include "../../LibCommon/NetworkLayer.h"
#define MAX_CIRCULAR_BUFFER_SIZE MAX_FEEDBACK_BUFFER_SIZE
#include "../../LibCommon/circular_buffer.h"
#include "../../LibCommon/my_filter.h"
/*==============================*
 * INCLUDES - Project Files     *
 *==============================*/
#include "btwam.h"
#include "bthaptics.h"
#include "btserial.h"

/*==============================*
 * PRIVATE DEFINED constants    *
 *==============================*/
enum{SCREEN_MAIN, SCREEN_HELP};

/*==============================*
 * GLOBAL file-scope variables  *
 *==============================*/
pthread_mutex_t disp_mutex;

int entryLine;

int useGimbals      = FALSE;
int done            = FALSE;

btstatecontrol *active_bts;

vect_n* active_pos;
vect_n* active_dest;
vect_n* jdest,*cdest;
vect_n* active_trq;
vect_n *wv;
double vel = 3.0,acc = 2.0;

int screen = SCREEN_MAIN;
int prev_mode;
char active_file[250];
char *user_def = "User edited point list";
wam_struct *wam;

vectray *vr;
via_trj_array **vta = NULL,*vt_j = NULL,*vt_c = NULL;
int cteach = 0;
extern int isZeroed;
static RT_TASK *mainTask;
btthread disp_thd,wam_thd;
double sample_rate;
btreal Jpos_filt[7];
btfilter *j5,*j6,*j7;
/******* Haptics *******/
btgeom_plane myplane,plane2,planes[10];
bteffect_wall mywall,wall[10];
bteffect_wickedwall mywickedwall,mywickedwall2,wickedwalls[10];
bthaptic_object myobject,myobject2,objects[20];
btgeom_sphere mysphere,mysphere2,spheres[10];
bteffect_bulletproofwall mybpwall,bpwall[10];
btgeom_box boxs[10];
bteffect_global myglobal;
vect_3 *p1,*p2,*p3,*zero_v3;
vect_3 *f1;
bthaptic_scene bth;
btgeom_state pstate;
char *command_help[100];
int num_commands;
double wamdata[8];
int NoSafety;

int zDown = 0;
PORT p;
int flip = 0;

/*==============================*
 * PRIVATE Function Prototypes  *
 *==============================*/
void sigint_handler();
void RenderMAIN_SCREEN(void);
void RenderHELP_SCREEN(void);
void RenderJOINTSPACE_SCREEN(void);
void RenderCARTSPACE_SCREEN(void);
void ProcessInput(int c);
void Shutdown(void);
void DisplayThread(void);
void StartDisplayThread(void);
void clearScreen(void);
void finish_entry(void);
void start_entry(void);
void init_ncurses(void);
void init_haptics(void);
void read_keys(char *filename);

//MOTORLAB
/*==============================*
 * DEFINES & VARIABLES          *
 *==============================*/
/*-----------------*
 * WAMcallback     *
 *-----------------*/
char DoPositionFollowing = 0;
char DoingPositionFollowing = 0;
char DoPositionBuffering = 0;
char WAMcallbackFlag = 0;
#define WC_UPDATE_POS		0x01
#define WC_READ_BUFFER		0x02
#define WC_CONSUME_BUFFER	0x04
#define WC_STEP_MODE		0x08 // Upon this flag, use ComputeNextPosStepMode instead of ComputeNextStep
#define WC_ALIGNMENT_SAMPLE	0x10 // Indicates that we should output an alignment pulse (allows us to figure out delay between spikes and robot command)
#define WC_STEP_MODE_TIMEOUT    0x20 //Indicates that step mode timed out! This indicates a serious bug in the Step Mode code
int  NumStepModeLoops = 0; //initialized by JumpToPosition, checked by IsStepModeDone

#define WC_SCHEDULING_PERIOD 0.002    //[sec] WAM control thread scheduling period
#define MAX_ORPHAN_TIME      0.010    //[sec] max time robot continues moving with no command updates
#define REMOTE_COMMANDS_INTERVAL 0.030 //[sec] time difference between remote commands (used for regular mode control)

#define MAX_JUMP_TO_POS_TIME 3//[sec] max time JumpToPosition will continue ramping to a position
#define MAX_JUMP_TO_POS_LOOPS (MAX_JUMP_TO_POS_TIME/WC_SCHEDULING_PERIOD)//[int] max number of times the control thread will run in step mode

/*-----------------*
 * General         *
 *-----------------*/
//variables used to exchange position between threads
#define MAX_ACC              10.0      //[rad/sec^2] Max acceleration value for regular control mode
#define MAX_VEL               5.0      //[rad/sec]   Max velocity value for regular control mode

#define EPSILON               0.000001 //Our notion of a very small amount
#define STEP_MAX_ACC          3.0      //[rad/sec^2] step mode's Max allowed acceleration
#define STEP_MAX_VEL          2.0      //[rad/sec] step mode's Max allowed velocity
#define STEP_POS_TOLERANCE   0.0001 //(STEP_MAX_VEL*WC_SCHEDULING_PERIOD + EPSILON)  //[rad]     step mode's abs() target achieved tolerance
#define STEP_VEL_TOLERANCE   (STEP_MAX_ACC*WC_SCHEDULING_PERIOD + EPSILON) //[rad/sec] step mode's abs() velocity at target tolerance

/*-----------------*
 * Positions       *
 *-----------------*/
 
//SAFE COORDINATES TO GOTO
#define J1_SAFE		(-0.20)
#define J2_SAFE		(-1.00)
#define J3_SAFE		(+0.70)
#define J4_SAFE		(+1.70)

//double HomePosition[ROBOT_NUM_JOINTS]={ 0, -1.57, 0, 3.09}; // Folded position (factory standard)
//double HomePosition[ROBOT_NUM_JOINTS]={ 0, -1.30, 0, 1.33}; // Extended position, wrist resting on front frame
double HomePosition[ROBOT_NUM_JOINTS]={ 0.771, -1.857, 0, 1.870}; // Elbow flexed, back and to the left in homing nest
double HomeToStartViaPos1[ROBOT_NUM_JOINTS]={ 0.771, -1.857, 0, 2.75}; // Elbow flexed above homing nest
//double HomeToStartViaPos1[ROBOT_NUM_JOINTS]={1.0, -1.857, 0, 1.870}; // Just above homing nest
//double HomeToStartViaPos2[ROBOT_NUM_JOINTS]={1.0, -0.8, 0, 2.75};
double StartTaskPosition[ROBOT_NUM_JOINTS]={0, -1.47, 0.25, 2.75};
//used to exchange position info with WAMcallback:
//
btreal JointRef[ROBOT_NUM_JOINTS]={0,0,0,0};

//
btreal JointPos[ROBOT_NUM_JOINTS]={0,0,0,0};

//Keeps track of latest SAMPLE_HEADER
SAMPLE_HEADER SampleHeader;
/*-----------------*
 * Limits          *
 *-----------------*/
typedef struct {
	double min[ROBOT_NUM_JOINTS];
	double max[ROBOT_NUM_JOINTS];
} JOINT_LIMITS_STRUCT;

JOINT_LIMITS_STRUCT HardJointLimits = {
	{-2.63,-1.95,-2.74,-0.78},
	{+2.65,+1.92,+2.81,+3.09}
};
	
JOINT_LIMITS_STRUCT TaskJointLimits = {
	{-1.65,-1.80,+0.34,+1.20},
	{+0.71,-0.88,+2.10,+3.09}
};

JOINT_LIMITS_STRUCT *curJointLimits;

/*-----------------*
 * Feedback        *
 *-----------------*/
//Buffer that gets filled with feedback values by the real-time thread every 2 msec
CIRCULAR_BUFFER CircularFeedbackBuffer[NUM_FEEDBACK_VARS][ROBOT_NUM_JOINTS];

// Serialized feedback data that gets sent to the client (i.e. values from CircularFeedbackBuffer)
FEEDBACK_BUFFER FeedbackOutputBuffer;

/*-----------------*
 * Path Generation *
 *-----------------*/
//Path generation modes
#define FILTER_LENGTH 30 

typedef enum { PM_NO_INTERPOLATION, PM_LINEAR, PM_PARABOLIC } PATH_MODE;

typedef struct {
	int    slow_down_flag;  //are we in slow down phase of the ramp [bool]
	double max_acc;         //maximal allowed acc     [rad/sec^2]
	double max_vel;         //maximal allowed vel     [rad/sec]
	int    done;            //is this joint done with its ramp [bool]
} StepSmoother;

typedef struct {
	double dest;            //latest external command [rad]
	double pid_command;     //PID command position    [rad]
	double prev_pid_command; //PID command at the previous 2msec control period [rad]
	double desired_path_point; //Interpolated trajectory output [rad]
	double limited_path_point; //Trajectory output with joint limits applied [rad]
	double vel;             //current velocity        [rad/sec]
	double max_acc;         //maximal allowed acc     [rad/sec^2]
	double max_vel;         //maximal allowed vel     [rad/sec]
	double remaining_time;  //remaining time until ext command should be reached [sec]
	double dt;              //PID step time           [sec]
	StepSmoother step;	//Step mode smoother variables
	int    joint_num;	//Joint number for this Smoother
	PATH_MODE mode;		//Path generation mode
	FILTER filter;          //For smoothing the command signal
	int use_filter;
} Smoother;

Smoother CommandSmoother[ROBOT_NUM_JOINTS];

/*-----------------*
 * Display         *
 *-----------------*/
//variables used by display thread
struct {
	char ListeningSocketOpen;
	char ClientConnected;
	char FollowRemotePosition;
	double CurCommandRad[ROBOT_NUM_JOINTS]; 
	double CurCommandDeg[ROBOT_NUM_JOINTS]; 
	char StepMode[ROBOT_NUM_JOINTS];
	char DebugFlag;
	char DebugInfo[100];  //used by all functions
	char DebugInfo2[100]; //used by display code to keep history of one line
	unsigned char GripperPos;
}DisplayInfo;


/*================================*
 * MOTORLAB Function Declerations *
 *================================*/
/*-----------------*
 * General         *
 *-----------------*/
void MyGlobalInit( void);
void ExitWAM( char *err);
int sign( double x);
double rad2deg( double x);
double deg2rad( double x);
/*-----------------*
 * Display         *
 *-----------------*/
void InitDisplayInfo();
void ResetDebugInfo();
/*----------------------*
 * Movement- high level *
 *----------------------*/
void FollowRemotePos( SOCKET_HANDLE sock);

int FollowPosition( double *dest, unsigned char gripper, int alignment_flag, int get_buffer, SOCKET_HANDLE sock);
int JumpToPosition( double *dest, unsigned char gripper, int get_buffer, SOCKET_HANDLE sock);
//flags for the consume argument in the XGetAndSendBuffer functions
#define DO_READ    0
#define DO_CONSUME 1
int GetAndSendBuffer( SOCKET_HANDLE sock, int consume);
int AskGetAndSendBuffer( SOCKET_HANDLE sock, int consume);

int SendEvent(SOCKET_HANDLE sock, int event_value);

/*-----------------*
 * Gripper         *
 *-----------------*/
#define GRIPPER_CMD_SHUTDOWN	255
#define GRIPPER_CMD_PING	200
#define GRIPPER_CMD_MIN		0
#define GRIPPER_CMD_MAX		55
#define GRIPPER_NO_CMD		253
#define GRIPPER_CMD_BAD		254
unsigned char GripperRef = GRIPPER_NO_CMD;
unsigned char GripperOutput = GRIPPER_NO_CMD;

unsigned char MapGripperCommand( double GripperPos);
int SendCommandToGripper( unsigned char c);
int IsGripperAlive( void);
int ShutdownGripper( void);
int WriteToSerialPort( unsigned char c);
int ReadFromSerialPort( unsigned char *buffer, int num_bytes);

void InitializeDigitalIO( void);
void DigitalOut( int bit0, int bit1);

/*----------------------*
 * Movement- low level  *
 *----------------------*/
void InitSmoother(Smoother* cs, double cur_position, int joint_num);
void InitStepSmoother(StepSmoother *step);

void ComputeNextPosStepMode( Smoother* cs);
int IsStepModeDone();
void ComputeNextStep(Smoother* cs);
void Interpolate0(Smoother* cs);
void InterpolateLinear(Smoother* cs);
void InterpolateParabolic(Smoother* cs);
void ComputeStepSize( double *NextCommand, double *JointPos, double *StepSize, int NumJoints);

void ApplyJointLimits( Smoother *SmootherArray);
void FilterCommand( Smoother *SmootherArray);
void CapVelocity(Smoother* cs, double MaxVel);


/*================================*
 * MOTORLAB Functions             *
 *================================*/
/*-----------------*
 * General         *
 *-----------------*/
void ExitWAM( char *err)
{
	if( err != NULL) 
		syslog( LOG_ERR, err);
	syslog( LOG_ERR, "ML: ExitWAM: Exiting the WAM Application");

	btthread_stop( &wam_thd); // Kill WAMControlThread
	CloseDL( &(wam->log));
	exit( 1);
}

int sign( double x)
{
	return ( x >= 0)? 1 : -1;
}

double rad2deg( double x)
{
	return 180.0 * x / PI;
}
double deg2rad( double x)
{
	return PI * x / 180.0;
}

/*-----------------*
 * Display         *
 *-----------------*/
//initialize the display info struct
void InitDisplayInfo()
{
	int i;
	DisplayInfo.ListeningSocketOpen = 0;
	DisplayInfo.ClientConnected     = 0;
	DisplayInfo.FollowRemotePosition= 0;
	for(i=0; i<ROBOT_NUM_JOINTS; i++) {
		DisplayInfo.CurCommandRad[i] = 0.0;
		DisplayInfo.CurCommandDeg[i] = 0.0;
		DisplayInfo.StepMode[i]      = 0;
	}
	DisplayInfo.DebugFlag =1;
	ResetDebugInfo();
}

void ResetDebugInfo()
{
	int i;
	for(i=0; i<sizeof(DisplayInfo.DebugInfo); i++)
	{
		DisplayInfo.DebugInfo[i] = 0;
		DisplayInfo.DebugInfo2[i] = 0;
	}
}

/*----------------------*
 * Movement- low level  *
 *----------------------*/
//initializes Smoother struct
void InitSmoother(Smoother* cs, double cur_position, int joint_num)
{
	cs->dest        = cur_position;
	cs->pid_command = cur_position;
	cs->prev_pid_command = cur_position;
	cs->desired_path_point = cur_position;
	cs->limited_path_point = cur_position;
	cs->vel         = 0.0;        
	cs->max_acc     = MAX_ACC;
	cs->max_vel     = MAX_VEL;
	cs->remaining_time = 0.0;
	cs->dt          = WC_SCHEDULING_PERIOD; 

	InitStepSmoother(&cs->step);
	cs->joint_num = joint_num;
	cs->mode      = PM_LINEAR;

	cs->use_filter = 1;
	InitializeFilter( &(cs->filter), FILTER_LENGTH, cur_position);
}

//Initialize StepSmoother struct
void InitStepSmoother( StepSmoother *step)
{
	step->slow_down_flag = 0;
	step->max_acc        = STEP_MAX_ACC;
	step->max_vel        = STEP_MAX_VEL;
	step->done           = 0;
}

void BeginStepMode( Smoother *cs)
{
	//double pid_velocity;
	
	//cs->desired_path_point = cs->pid_command;
	//pid_velocity = (cs->pid_command - cs->prev_pid_command) / cs->dt;
	//cs->vel = pid_velocity;
}

void EndStepMode( Smoother* cs)
{
	cs->vel = 0;
	cs->desired_path_point = cs->dest;	
	cs->step.done = 1;
	cs->step.slow_down_flag = 0;
	DisplayInfo.StepMode[cs->joint_num] = 0;
}

//computes a ramp that advances to the required destination
void ComputeNextPosStepMode( Smoother* cs)
{
	double delta_pos, hypothetical_delta_pos, remaining_distance; 
	double final_velocity;
	double acc;
	double step_size, max_possible_step;
	double vel_step;

	if(cs->step.done)
		return;
	
	delta_pos = cs->dest - cs->desired_path_point;
	remaining_distance = fabs( delta_pos);

	//If not already in the slow-down phase
	if( !cs->step.slow_down_flag)
	{
		//Check if we are at the destination with velocity close to zero
		if( (remaining_distance < STEP_POS_TOLERANCE) && (fabs(cs->vel) < STEP_VEL_TOLERANCE))
		{
			//this is a special case for the times we are already at the target with near zero velocity when this function is called
			EndStepMode( cs);
			return;
		}	       

		// Calculate whether at this point we can start slowing down towards the
		// target, otherwise go toward target as fast as possible

		// Check current movement direction
		if( sign( delta_pos) == sign( cs->vel)) 
		{   // movement is TOWARDS the target

			// Calculate distance it takes to come to a perfect stop at the
			// target starting at the current state using maximal deceleration   
			// The equation for this is: DeltaX = (v^2 - v0^2) / (2*a)
			final_velocity = 0;
			hypothetical_delta_pos = (final_velocity*final_velocity - (cs->vel)*(cs->vel)) / (2*(cs->step.max_acc));

			if( fabs(hypothetical_delta_pos) >= remaining_distance)
			{
				// Go into slow-down phase
				cs->step.slow_down_flag = 1;
			}else{
				// Should not go into slow-down phase yet
				cs->step.slow_down_flag = 0;
			}
		}else{
			// movement is AWAY FROM the target
			cs->step.slow_down_flag = 0;
		}
	}

	if( cs->step.slow_down_flag)
	{
		// Calculate acceleration required to come to a perfect stop at the
		// target starting at the current state    
		// The equation for this is: a = (v^2 - v0^2) / (2*DeltaX)
		final_velocity = 0;
		acc = -( fabs( final_velocity*final_velocity - cs->vel*cs->vel) / (2*delta_pos));
		vel_step = acc * cs->dt;
		cs->vel = cs->vel + vel_step;
		max_possible_step = cs->vel * cs->dt;
		//if( remaining_distance < max_possible_step)
		if( remaining_distance < STEP_POS_TOLERANCE)
		{
			EndStepMode( cs);
			return;
		}else{
			// Verify whether the velocity change would be too large in one step so that it
			// would reverse direction due to numerical integration error
			if( fabs( vel_step) > fabs( cs->vel) ) {
				EndStepMode( cs);
				return;
			}
		}
	}else{
		acc = sign( delta_pos) * cs->step.max_acc; // accelerate towards target
		cs->vel = cs->vel + acc * cs->dt;
	}

	CapVelocity(cs, cs->step.max_vel);

	// Determine the next PID pos
	step_size = cs->vel * cs->dt;
	cs->desired_path_point = cs->desired_path_point + step_size;
}

/*
 * Returns 0 if step mode has not terminated
 *         1 if step mode has terminated
 *         2 if step mode has timed out
 */
int IsStepModeDone()
{
	Smoother *cs = CommandSmoother;
	int i;
	int done = 1;

	//check if step mode has run for too long
	if(--NumStepModeLoops <= 0)
	{
		syslog(LOG_ERR, "ML: IsStepModeDone: Jump command timed out!");
		return 2;
	}

	//syslog(LOG_ERR,"ML: IsStepModeDone: step.done = [%i %i %i %i]", cs[0].step.done, cs[1].step.done, cs[2].step.done, cs[3].step.done);
	for(i=0; i<ROBOT_NUM_JOINTS; i++)
		if(!cs[i].step.done) done = 0;
	
	return done;	
}

//computes the next PID step smoothly
void ComputeNextStep(Smoother* cs)
{
	switch(cs->mode)
	{
		case PM_NO_INTERPOLATION:
			Interpolate0( cs);
			break;
		case PM_LINEAR:
			InterpolateLinear( cs);
			break;
		case PM_PARABOLIC:
			InterpolateParabolic( cs);
			break;
		default:
			break;
	}	
}

//Sets next step equal to remote command without any interpolation
void Interpolate0(Smoother* cs)
{
	cs->vel = (cs->dest - cs->desired_path_point) / REMOTE_COMMANDS_INTERVAL;
	cs->desired_path_point = cs->dest;
}

//computes the next step using linear interpolation
void InterpolateLinear(Smoother* cs)
{
	double remaining_distance; 
	double step_size;

	// Compute updated velocity if current command end time not reached yet	
	if( cs->remaining_time > 0)
	{
		remaining_distance = cs->dest - cs->desired_path_point;
		cs->vel  = (remaining_distance/ cs->remaining_time);
	
	}else if( cs->remaining_time < -MAX_ORPHAN_TIME) {
		//syslog( LOG_ERR, "ML: InterpolateLinear: InterpolateLinear: Orphaned for %.3f seconds", -cs->remaining_time);
		cs->vel = 0;
	}
	
	CapVelocity(cs, cs->max_vel);
	
	//Determine the next desired PID pos
	step_size = cs->vel * cs->dt;
	cs->desired_path_point = cs->desired_path_point + step_size;
	cs->remaining_time = cs->remaining_time - cs->dt;
}

//computes the next PID step smoothly
void InterpolateParabolic(Smoother* cs)
{
	double remaining_distance; 
	double hyp_vel;
	double hyp_vel_change;
	double max_possible_vel_change;
	double step_size;

	// Compute updated velocity if current command end time not reached yet	
	if( cs->remaining_time > 0)
	{
		remaining_distance = cs->dest - cs->desired_path_point;
		hyp_vel  = (remaining_distance/ cs->remaining_time);
		hyp_vel_change = hyp_vel - cs->vel;
		max_possible_vel_change = cs->max_acc * cs->dt;


		//Limit the acceleration
		if (fabs(hyp_vel_change) < max_possible_vel_change)
		{
			cs->vel = hyp_vel; 
		}else{ 
			if (hyp_vel_change > 0)//need to accelerate
				cs->vel = cs->vel + max_possible_vel_change;
			else //need to decelerate
				cs->vel = cs->vel - max_possible_vel_change;
		}

		//Cap the velocity to a maximum value
		CapVelocity(cs, cs->max_vel);
	}else if( cs->remaining_time < -MAX_ORPHAN_TIME) {
		//syslog( LOG_ERR, "ML: InterpolateParabolic: Orphaned for %.3f seconds", -cs->remaining_time);
		cs->vel = 0;
	}
	
	//Determine the next PID pos
	step_size = cs->vel * cs->dt;
	cs->desired_path_point = cs->desired_path_point + step_size;
	cs->remaining_time = cs->remaining_time - cs->dt;
}

//calculates a step size based on the distance between current position & command position
void ComputeStepSize( double *NextCommand, double *JointPos, double *StepSize, int NumJoints)
{
	int i;
	double Diff;
	double SamplesPerCommand = 22.0;
	for( i = 0; i < NumJoints; i++) 
	{
		Diff = NextCommand[i] - JointPos[i];
		StepSize[i] = Diff / SamplesPerCommand;
	}
}

void ApplyJointLimits( Smoother *SmootherArray)
{
	int i;
	JOINT_LIMITS_STRUCT *lim;
	Smoother *s;
	
	// Pointer sanity check
	if( curJointLimits != &HardJointLimits && curJointLimits != &TaskJointLimits)
		ExitWAM( "ML: ApplyJointLimits: Joint limits structure pointer is invalid");

	lim = curJointLimits;
	for( i = 0; i < ROBOT_NUM_JOINTS; i++)
	{
		s = &(SmootherArray[i]);
		s->limited_path_point = s->desired_path_point;
		if( s->desired_path_point < lim->min[i])
		{
			s->limited_path_point = lim->min[i];
			//syslog(LOG_ERR, "ML: ApplyJointLimits: Min limited joint %d\t\t",i);
		}
		if( s->desired_path_point > lim->max[i])
		{	
			s->limited_path_point = lim->max[i];
			//syslog(LOG_ERR, "ML: ApplyJointLimits: Max limited joint %d\t\t",i);
		}
	}
}

void FilterCommand( Smoother *SmootherArray)
{
	int i;
	Smoother *s;
	double filtered_sample;

	for( i = 0; i < ROBOT_NUM_JOINTS; i++)
	{
		s = &(SmootherArray[i]);
		filtered_sample = FilterSample( &(s->filter), s->limited_path_point);
		s->prev_pid_command = s->pid_command;
		if( s->use_filter)
			s->pid_command = filtered_sample;
		else
			s->pid_command = s->limited_path_point;
	}
}

// Limits the velocity to the given value
void CapVelocity(Smoother* cs, double MaxVel)
{
	if( cs->vel >  MaxVel)  cs->vel =  MaxVel;
	if( cs->vel < -MaxVel)  cs->vel = -MaxVel;
}

//////////////////////////////////////////////////////
// Hand stuff
int HandError = 0;

#define NUM_HAND_JOINTS 4

int IsFirstHandLoop = 1;

typedef struct {
	int use_velocity[NUM_HAND_JOINTS];
	int use_strain[NUM_HAND_JOINTS];
	int use_abs_position[NUM_HAND_JOINTS];
	int use_delta_position[NUM_HAND_JOINTS];
	int use_temperature;
} HAND_FEEDBACK_CONFIG;

typedef struct {
	double velocity[NUM_HAND_JOINTS];
	double strain[NUM_HAND_JOINTS];
	double abs_position[NUM_HAND_JOINTS];
	double delta_position[NUM_HAND_JOINTS];
	double temperature;
} HAND_FEEDBACK;

typedef struct {
	int use_velocity[NUM_HAND_JOINTS];
	int use_prop_gain[NUM_HAND_JOINTS];
} HAND_COMMAND_CONFIG;

typedef struct {
	double velocity[NUM_HAND_JOINTS];
	double prop_gain[NUM_HAND_JOINTS];
} HAND_COMMAND;

HAND_FEEDBACK_CONFIG HandFeedbackConfig = {0};
HAND_COMMAND_CONFIG HandCommandConfig = {0};
int HandConfigured = 0;

FILE *HandDebugFile = NULL;
void InitializeHandDebugging( void)
{
#ifdef DEBUG_HAND
	HandDebugFile = fopen( "HandDebugFile.txt", "wt");
#endif // DEBUG_HAND
}

void FinishHandDebugging( void)
{
#ifdef DEBUG_HAND
	fclose( HandDebugFile);
#endif // DEBUG_HAND
}

void PrintHandDebugByte( char c)
{
#ifdef DEBUG_HAND
	fprintf( HandDebugFile, "[%hhu]", (unsigned char) c);
	fflush( HandDebugFile);
#endif // DEBUG_HAND
}

void PrintHandDebugBytes( char *buf, int num_bytes)
{
#ifdef DEBUG_HAND
	char c;
	int i;
	for( i = 0; i < num_bytes; i++) {
		c = buf[i];
		fprintf( HandDebugFile, "[%hhu]", (unsigned char) c);
	}
	fflush( HandDebugFile);
#endif // DEBUG_HAND
}

void PrintHandDebugChar( char c)
{
#ifdef DEBUG_HAND
	if( c == 10) c = '~';
	if( c == 13) c = '|';
	if( c < 32 || c > 126) {
		fprintf( HandDebugFile, "[%hhu]", (unsigned char) c);
	} else {
		fprintf( HandDebugFile, "%c", c);
	}
	fflush( HandDebugFile);
#endif // DEBUG_HAND
}

void PrintHandDebugString( char *string)
{
#ifdef DEBUG_HAND
	int string_length;
	int i;
	char c;
	
	string_length = strlen( string);
	for( i = 0; i < string_length; i++) {
		c = string[i];
		if( c == 10) c = '~';
		if( c == 13) c = '|';
		if( c < 32 || c > 126) {
			fprintf( HandDebugFile, "[%hhu]", (unsigned char) c);
		} else {
			fprintf( HandDebugFile, "%c", c);
		}
	}
	fflush( HandDebugFile);
#endif // DEBUG_HAND
}

void PrintHandDebugNewline( void)
{
#ifdef DEBUG_HAND
	fprintf( HandDebugFile, "\n");
	fflush( HandDebugFile);
#endif // DEBUG_HAND
}

void PrintHandDebugText( char *text)
{
#ifdef DEBUG_HAND
	fprintf( HandDebugFile, "%s\n", text);
	fflush( HandDebugFile);
#endif // DEBUG_HAND
}

int serialWriteBytes( PORT *port, char *buf, int bytesToWrite)
{
	int return_value;

	PrintHandDebugString( "WB_BEGIN-<");
	return_value = write( port->ofd, buf, bytesToWrite);
	if( return_value < 0) {
		PrintHandDebugString( ">-WB_ERROR");
		return return_value;
	}
	if( return_value >= 0 && return_value < bytesToWrite) {
		PrintHandDebugBytes( buf, return_value);
		PrintHandDebugString( ">-WB_INCOMPLETE");
		return 1;
	}
	if( return_value > bytesToWrite) {
		PrintHandDebugBytes( buf, bytesToWrite);
		PrintHandDebugString( ">-WB_OVERWRITE");
		return 2;
	}
	PrintHandDebugBytes( buf, bytesToWrite);
	PrintHandDebugString( ">-WB_END");
	return 0;
}

int serialBytesAvailable( void)
{
	int bytes_available;
	char buf[100];
	//read( p.ifd, buf, 0);
	ioctl( p.ifd, FIONREAD, &bytes_available);
	return bytes_available;
}

int serialReadBytes( PORT *port, char *buf, int bytesRequested)
// Reads specified number of bytes from serial port if available,
// or if not enough bytes are available, then reads whatever is
// available. Returns the number of bytes actually read or
// a negative error code if a read error occurred.
{
	int return_value;
	int bytes_read, bytes_available;
	int bytesToRead;

	PrintHandDebugString( "RB_BEGIN-<");
	
	bytesToRead = bytesRequested;
	bytes_available = serialBytesAvailable( );
	if( bytes_available < bytesRequested) bytesToRead = bytes_available;
	return_value = read( port->ifd, buf, bytesToRead);
	if( return_value < 0) {
		PrintHandDebugString( ">-RB_ERROR");
		return return_value;
	}
	bytes_read = return_value;
	PrintHandDebugBytes( buf, bytes_read);
	if( bytes_read < bytesToRead) {
		PrintHandDebugString( ">-RB_INCOMPLETE");
		return bytes_read;
	}
	if( bytes_read < bytesRequested) {
		PrintHandDebugString( ">-RB_PARTIAL");
		return bytes_read;
	}
	PrintHandDebugString( ">-RB_END");
	return bytes_read;
}

int serialWriteText( PORT *port, char *buf)
{
	int return_value;
	int bytesToWrite;
	char buf_copy[1000];

	bytesToWrite = strlen( buf);
	PrintHandDebugString( "WT_BEGIN-{");
	return_value = write( port->ofd, buf, bytesToWrite);
	if( return_value < 0) {
		PrintHandDebugString( "}-WT_ERROR");
		return return_value;
	}
	if( return_value >= 0 && return_value < bytesToWrite) {
		strcpy( buf_copy, buf);
		buf_copy[return_value] = 0;
		PrintHandDebugString( buf_copy);
		PrintHandDebugString( "}-WT_INCOMPLETE");
		return 1;
	}
	if( return_value > bytesToWrite) {
		sprintf( buf_copy, "%s...", buf);
		PrintHandDebugString( buf_copy);
		PrintHandDebugString( "}-WT_OVERWRITE");
		return 2;
	}
	PrintHandDebugString( buf);
	PrintHandDebugString( "}-WT_END");
	return 0;
}

int serialReadText( PORT *port, char *buf, char *delimiter, int TimeOutSeconds)
// Reads text from serial port up to and including the delimeter character sequence.
// If the delimiter is not encountered within TimeOutSeconds, then the function returns
// whatever it was able to read. The text returned in buf is zero-terminated.
// Returns 0 if delimiter found, 1 if timed out or a negative error code if there was a read error.
{
	int return_value;
	int dataIndex;
	char Char;
	int usWaited;
	int delimiter_found;
	int delimiter_length;
	int i;

	PrintHandDebugString( "RT_BEGIN-{");
	
	delimiter_length = strlen( delimiter);
	dataIndex = 0;
	usWaited = 0;
	delimiter_found = 0;
	buf[0] = 0;
	while( !delimiter_found) {
		// Read one character
		return_value = read( port->ifd, &Char, 1);
		if( return_value < 0) {
			PrintHandDebugString( "}-RT_ERROR");
			return return_value;
		}
		// If a character was read, then process it
		if( return_value > 0) {
			// Put it in the output buffer
			buf[dataIndex] = Char;
			dataIndex++;
			buf[dataIndex] = 0; // zero-terminate string
			PrintHandDebugChar( Char);
			// See if we found the delimiter character sequence
			if( dataIndex >= delimiter_length) {
				delimiter_found = 1;
				for( i = 0; i < delimiter_length; i++) {
					if( buf[dataIndex-delimiter_length+i] != delimiter[i]) delimiter_found = 0;
				}
			}
		}
		// See if timeout reached yet
		if( !delimiter_found) {
			if( usWaited > TimeOutSeconds*1000000) {
				PrintHandDebugString( "}-RT_TIMEOUT");
				return 1;
			}
			usleep( 10000);
			usWaited += 10000;
		}
	}
	PrintHandDebugString( "}-RT_END");
	return 0;
}

int ReadHandTextResponse( char *buf)
// Read text response from hand in supervisory mode. Outputs a zero-terminated string
// in buf. Times out after 10 seconds, because
// 10 seconds is enough time for the longest command (HI) to execute. If timed out,
// then buf will contain whatever characters were successfully read.
// Return value is 0 if a full response received, 1 if timed out before receiving full
// response, or a negative error code if a read error occurred.
{
	int return_value;
	
	// Read everything up to and including the prompt "=> " for next command.
	return_value = serialReadText( &p, buf, "=> ", 10);
	PrintHandDebugNewline( );
	return return_value;
}

int SendHandTextCommand( char *buf)
// Send a text command to the BarrettHand in supervisory mode. This function automatically
// appends the '\r' character, so the input string only needs to contain the desired command.
// Returns 0 on successful write to serial port, 1 on incomplete write, 2 on writing too many bytes
// and a negative error code on write error.
{
	int return_value;
	char buf_copy[1000];

	sprintf( buf_copy, "%s\r", buf);
	return_value = serialWriteText( &p, buf_copy);
	PrintHandDebugNewline( );
	return return_value;
}

int ExecuteHandTextCommand( char *command)
{
	int status;
	char response[10000];
	
	status = SendHandTextCommand( command);
	if( status != 0) {
		sprintf( DisplayInfo.DebugInfo, "Gripper command send ERROR (%i)", status);
		return -1;
	}
	status = ReadHandTextResponse( response);
	if( status != 0) {
		sprintf( DisplayInfo.DebugInfo, "Gripper response receive ERROR (%i)", status);
		return -2;
	}
	//***Parse response to see if there was an error
	return 0;
}

int StartHandRealtimeMode( char *motor_prefix)
{
	int status;
	char response[10000];
	char command[100];
	
	sprintf( command, "%sLOOP", motor_prefix);
	status = SendHandTextCommand( command);
	if( status != 0) {
		sprintf( DisplayInfo.DebugInfo, "Failed to send LOOP command (ERROR %i)", status);
		return -1;
	}
	status = serialReadText( &p, response, "*", 1);
	if( status != 0) {
		sprintf( DisplayInfo.DebugInfo, "Failed to receive response to LOOP command (ERROR %i)", status);
		return -2;
	}
	//***Parse response to see if there was an error
	PrintHandDebugNewline( );
	return 0;
}

int ClearHandFeedbackBuffer( void)
// Clears the incoming serial buffer. Returns the number of bytes discarded or a negative
// error code on read error.
{
	int return_value;
	char buf[1000];
	int totalBytesRead = 0;
	
	while( serialBytesAvailable( ) > 0) {
		return_value = serialReadBytes( &p, buf, 1000);
		if( return_value < 0) {
			PrintHandDebugNewline( );
			return return_value;
		}
		totalBytesRead += return_value;
	}
	PrintHandDebugNewline( );
	return totalBytesRead;
}

int ConfigureHand( void)
{
	char config_command[1000];
	int i;
	
	// Initialize global hand config structures to zero
	memset( &HandFeedbackConfig, 0, sizeof(HAND_FEEDBACK_CONFIG));
	memset( &HandCommandConfig, 0, sizeof(HAND_COMMAND_CONFIG));
	
	// Set feedback parameters
	HandFeedbackConfig.use_velocity[0] = 0;
	HandFeedbackConfig.use_velocity[1] = 0;
	HandFeedbackConfig.use_velocity[2] = 0;
	HandFeedbackConfig.use_velocity[3] = 0;
	
	HandFeedbackConfig.use_strain[0]   = 1;
	HandFeedbackConfig.use_strain[1]   = 0;
	HandFeedbackConfig.use_strain[2]   = 0;
	HandFeedbackConfig.use_strain[3]   = 0;

	HandFeedbackConfig.use_abs_position[0] = 0;
	HandFeedbackConfig.use_abs_position[1] = 0;
	HandFeedbackConfig.use_abs_position[2] = 0;
	HandFeedbackConfig.use_abs_position[3] = 0;
	
	HandFeedbackConfig.use_delta_position[0] = 0;
	HandFeedbackConfig.use_delta_position[1] = 0;
	HandFeedbackConfig.use_delta_position[2] = 0;
	HandFeedbackConfig.use_delta_position[3] = 0;

	HandFeedbackConfig.use_temperature = 0;

	// Set control parameters
	HandCommandConfig.use_velocity[0] = 1;
	HandCommandConfig.use_velocity[1] = 0;
	HandCommandConfig.use_velocity[2] = 0;
	HandCommandConfig.use_velocity[3] = 0;

	HandCommandConfig.use_prop_gain[0] = 0;
	HandCommandConfig.use_prop_gain[1] = 0;
	HandCommandConfig.use_prop_gain[2] = 0;
	HandCommandConfig.use_prop_gain[3] = 0;
	
	// Reset the hand back to supervisory mode if it is in real-time mode and
	// Clear the serial input buffer
	ExecuteHandTextCommand( ""); // This has the effect of pulling hand out of real-time mode if it is in real-time mode
	PrintHandDebugText( "Clearing feedback buffer");
	ClearHandFeedbackBuffer( );
	
	// Send parameter selections to hand
	PrintHandDebugText( "Sending config parameters");
	
	for( i = 0; i < NUM_HAND_JOINTS; i++) {
		sprintf( config_command, "%iFSET LCV %i", i+1, HandCommandConfig.use_velocity[i]);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LCVC %i", i+1, 1);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LCPG %i", i+1, HandCommandConfig.use_prop_gain[i]);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LFV %i", i+1, HandFeedbackConfig.use_velocity[i]);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LFVC %i", i+1, 1);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LFS %i", i+1, HandFeedbackConfig.use_strain[i]);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LFAP %i", i+1, HandFeedbackConfig.use_abs_position[i]);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LFDP %i", i+1, HandFeedbackConfig.use_delta_position[i]);
		if( ExecuteHandTextCommand( config_command)) return -1;
		
		sprintf( config_command, "%iFSET LFDPC %i", i+1, 1);
		if( ExecuteHandTextCommand( config_command)) return -1;
	}
	sprintf( config_command, "PSET LFT %i", HandFeedbackConfig.use_temperature);
	if( ExecuteHandTextCommand( config_command)) return -1;

	// Put the hand in real-time control mode
	PrintHandDebugText( "Sending the LOOP command");
	if( StartHandRealtimeMode( "")) return -2;
	PrintHandDebugText( "Real-time mode is active");
	
/*
	ExecuteHandTextCommand( "12FSET LCV 1 LCVC 1 LCPG 0 LFV 0 LFS 1 LFAP 0 LFDP 1 LFDPC 1");
	ExecuteHandTextCommand( "4FSET LCV 0 LCPG 0 LFV 0 LFS 0 LFAP 0 LFDP 1 LFDPC 1");
	ExecuteHandTextCommand( "PSET LFT 1");
	StartHandRealtimeMode( "124");
*/	
	HandConfigured = 1;
	return 0;
}


//////////////////////// Real-time hand functions
int GetHandFeedback( HAND_FEEDBACK *f)
{
	char header, buf[100];
	int bytes_to_read, bytes_read;
	int return_value;
	int i;
	union {
		char *byte;
		signed char *int8;
		unsigned char *uint8;
		signed short *int16;
		unsigned short *uint16;
	} pData;
	
	// During the first loop iteration we only get a feedback header.
	// Feedback data is only available starting from the second loop iteration
	if( IsFirstHandLoop) {
		IsFirstHandLoop = 0;
	} else {
		// Decide how many bytes are expected in the feedback data block
		bytes_to_read = 1; // one byte for header
		for( i = 0; i < NUM_HAND_JOINTS; i++) if( HandFeedbackConfig.use_velocity[i]) bytes_to_read += 1;
		for( i = 0; i < NUM_HAND_JOINTS; i++) if( HandFeedbackConfig.use_strain[i]) bytes_to_read += 1;
		for( i = 0; i < NUM_HAND_JOINTS; i++) if( HandFeedbackConfig.use_abs_position[i]) bytes_to_read += 2;
		for( i = 0; i < NUM_HAND_JOINTS; i++) if( HandFeedbackConfig.use_delta_position[i]) bytes_to_read += 1;
		if( HandFeedbackConfig.use_temperature) bytes_to_read += 2;

		// Add another 4 bytes to clear the stupid dummy characters the hand seems to send
		bytes_to_read += 4;

		// Read feedback block
		return_value = serialReadBytes( &p, buf, bytes_to_read);
		PrintHandDebugNewline( );
		if( return_value < 0) {
			PrintHandDebugText( "Read error while trying to read feedback block");
			return -1;
		}
		bytes_read = return_value;
		
		// Parse header
		if( bytes_read < 1) {
			PrintHandDebugText( "Zero bytes read while trying to read feedback block");
			return -2;
		}
		header = buf[0];
		switch( header) {
			case '*':
				// '*' is the normal header, so if we got it then it's cool
				break;
			case 0x0D:
				// This means there is an error, so quit
				PrintHandDebugText( "Hand returned an error");
				sprintf( DisplayInfo.DebugInfo, "Hand Real-time feedback returned error");
				return -3;
			default:
				PrintHandDebugText( "Hand returned unknown feedback header");
				sprintf( DisplayInfo.DebugInfo, "Unknown Hand Real-time feedback header (%u)", (unsigned int) header);
				return -4;
		}
		
		// Check number of total bytes
		if( bytes_read < bytes_to_read) {
			PrintHandDebugText( "Not enough feedback bytes were read");
			sprintf( DisplayInfo.DebugInfo, "Not enough bytes read from Hand feedback");
			return -5;
		}


		// Parse individual data items from the feedback block
		pData.byte = buf;
		memset( f, 0, sizeof(HAND_FEEDBACK));
		for( i = 0; i < NUM_HAND_JOINTS; i++) {
			if( HandFeedbackConfig.use_velocity[i]) {
				signed char velocity = *(pData.int8);
				f->velocity[i] = (double) velocity;
				pData.byte += 1;
			}
			if( HandFeedbackConfig.use_strain[i]) {
				unsigned char strain = *(pData.uint8);
				f->strain[i] = (double) strain;
				pData.byte += 1;
			}
			if( HandFeedbackConfig.use_abs_position[i]) {
				unsigned short abs_position = *(pData.uint16);
				f->abs_position[i] = (double) abs_position;
				pData.byte += 2;
			}
			if( HandFeedbackConfig.use_delta_position[i]) {
				signed char delta_position = *(pData.int8);
				f->delta_position[i] = (double) delta_position;
				pData.byte += 1;
			}
		}
		if( HandFeedbackConfig.use_temperature) {
			signed short temperature = *(pData.int16);
			f->temperature = 0.1 * ((double) temperature);
			pData.byte += 2;
		}
	}
	return 0;
}

int round( double x)
{
	if( x >= 0) return (int) (x + 0.5);
	else return (int) (x - 0.5);
}

int SendHandCommand( HAND_COMMAND *c)
{
	char header, buf[100];
	int bytes_to_write;
	int i;
	union {
		char *byte;
		signed char *int8;
		unsigned char *uint8;
	} pData;
	int return_value;
	char str[100];

	// Based on configuration, decide header character to use and construct command buffer
	pData.byte = buf + 1;
	bytes_to_write = 1;
	header = 'A';
	for( i = 0; i < NUM_HAND_JOINTS; i++) {
		if( HandCommandConfig.use_velocity[i]) {
			*(pData.int8) = (signed char) round( c->velocity[i]);
			header = 'C';
			bytes_to_write += 1;
			pData.byte += 1;
		}
		if( HandCommandConfig.use_prop_gain[i]) {
			*(pData.uint8) = (unsigned char) round( c->prop_gain[i]);
			header = 'C';
			bytes_to_write += 1;
			pData.byte += 1;
		}
	}
	buf[0] = header;

	// Send command block
	return_value = serialWriteBytes( &p, buf, bytes_to_write);
	PrintHandDebugNewline( );
	if( return_value != 0) {
		sprintf( DisplayInfo.DebugInfo, "Failed to write Hand command to serial port");
		return -1;
	}
	return 0;
}

HAND_FEEDBACK HandFeedback = {0};
HAND_COMMAND HandCommand = {0};
int HandLoopCounter = 0;
	
// Implement hand control
void ControlHand( void)
{
	int status;
	
	if( HandError) {
		if( serialBytesAvailable( ) > 0) ClearHandFeedbackBuffer( );
	} else {

		if( HandLoopCounter % 4 == 0) {

			PrintHandDebugString( ".");

			status = GetHandFeedback( &HandFeedback);
			if( status != 0) {
				sprintf( DisplayInfo.DebugInfo, "Hand Real-time Feedback Error");
				HandError = 1;
				return;
			}

			HandCommand.velocity[0] = -123;

			status = SendHandCommand( &HandCommand);
			if( status != 0) {
				sprintf( DisplayInfo.DebugInfo, "Hand Realtime Command Error");
				HandError = 1;
				return;	
			}
		}
		HandLoopCounter++;
	}
}

// End Hand Stuff
/////////////////////////////////////////////

/*-----------------*
 * WAMcallback     *
 *-----------------*/
int WAMcallback(struct btwam_struct *wam)
{
	int i, v;
	int read_buffer, consume_buffer;
	int update_pos, alignment_sample;
	int use_step_mode;
	char flag;
	int num_points, gripper_status;
	int SampleClockPulse, AlignmentPulse;
	int step_mode_done, step_mode_timeout;

	if( HandConfigured) ControlHand( );
	
	// Keep a notion of the latest actual position (from encoders)
	for( i = 0; i < ROBOT_NUM_JOINTS; i++)
		JointPos[i] = wam->Jpos->q[i];

	//sprintf(DisplayInfo.DebugInfo2, "[X,Y,Z] = [%f %f %f]", wam->R6pos->q[0]*1000+X_TRANSFORM_BARRETT_2_ML, wam->R6pos->q[2]*1000+Y_TRANSFORM_BARRETT_2_ML, wam->R6pos->q[1]*1000+Z_TRANSFORM_BARRETT_2_ML);	
	//sprintf(DisplayInfo.DebugInfo2, "[X,Y,Z] = [%f %f %f]", wam->R6pos->q[0]*1000, wam->R6pos->q[1]*1000, wam->R6pos->q[2]*1000);
	//sprintf(DisplayInfo.DebugInfo2, "%f %f %f", wam->Cpos->q[0], wam->Cpos->q[1],  wam->Cpos->q[2]);
	
	// Acknowledge change of position following status
	DoingPositionFollowing = DoPositionFollowing ? 1 : 0;

	if( DoingPositionFollowing ) 
	{

		// Check flags in a manner that is atomic
		flag = WAMcallbackFlag;//take local snapshot of the flags
		update_pos     = check_flag_bits( flag, WC_UPDATE_POS)    ? 1 : 0;
		read_buffer    = check_flag_bits( flag, WC_READ_BUFFER)   ? 1 : 0;
		consume_buffer = check_flag_bits( flag, WC_CONSUME_BUFFER)? 1 : 0;
		use_step_mode  = check_flag_bits( flag, WC_STEP_MODE)     ? 1 : 0;
		step_mode_timeout = check_flag_bits( flag, WC_STEP_MODE_TIMEOUT) ? 1 : 0;	
		alignment_sample = check_flag_bits( flag, WC_ALIGNMENT_SAMPLE)? 1 : 0;

		clear_flag_bits( WAMcallbackFlag, WC_ALIGNMENT_SAMPLE);
		
		//in case we had an internal error - we will not move anymore until it is cleared
		if(!step_mode_timeout)
		{
				//this statement will be executed only when a remote command position has been received
				if( update_pos)
				{
					// Update the path generator's idea of command position
					for( i = 0; i < ROBOT_NUM_JOINTS; i++)
					{
						CommandSmoother[i].dest = JointRef[i];
						CommandSmoother[i].remaining_time = REMOTE_COMMANDS_INTERVAL;
						if(use_step_mode) BeginStepMode( &CommandSmoother[i]);
					}
					// Send command to gripper
					gripper_status = SendCommandToGripper(GripperRef);
					if(gripper_status != 1) {
						ResetDebugInfo(); sprintf( DisplayInfo.DebugInfo, "WAMcallback: Gripper command unsuccessful: SendCommand returned %i\t",gripper_status );
						//syslog( LOG_ERR, "ML: WAMcallback: SendCommandToGripper returned %i", gripper_status);
					}
					clear_flag_bits( WAMcallbackFlag, WC_UPDATE_POS);
				}

				//this statement will be executed on every iteration of WAMcallback
				// Calculate next path point
				if( use_step_mode)
				{
					if( step_mode_done = IsStepModeDone( ))
					{
						if(step_mode_done == 1)
						{//normal termination of step mode
							for(i=0; i < ROBOT_NUM_JOINTS; i++)
							{
								CommandSmoother[i].step.done = 0;
								//CommandSmoother[i].use_filter = 1;
							}
							clear_flag_bits( WAMcallbackFlag, WC_STEP_MODE);
						}else if(step_mode_done == 2)
						{//step mode timed out - this is an internal ERROR!
							ResetDebugInfo(); sprintf( DisplayInfo.DebugInfo, "WAMcallback: ERROR: Step Mode has timed out!! \t" );
							syslog(LOG_ERR, "ML: WAMcallback: IsStepModeDone() returned 2: StepMode timed out");
							set_flag_bits(WAMcallbackFlag, WC_STEP_MODE_TIMEOUT);
							
							for(i=0; i < ROBOT_NUM_JOINTS; i++)
								CommandSmoother[i].step.done = 0;
							clear_flag_bits( WAMcallbackFlag, WC_STEP_MODE);
						}
					}else{
						for( i = 0; i < ROBOT_NUM_JOINTS; i++)
						{
							ComputeNextPosStepMode( &CommandSmoother[i]);
							//CommandSmoother[i].use_filter = 0;
						}
					}
				}else{//Follow remote command mode
					for( i = 0; i < ROBOT_NUM_JOINTS; i++) 
						ComputeNextStep( &CommandSmoother[i]);
				}
			
				// Apply limits to path point, set PID command
				ApplyJointLimits( CommandSmoother);

				// Filter the PID command
				FilterCommand( CommandSmoother);

				// Give PID command to the WAM
				for( i = 0; i < ROBOT_NUM_JOINTS; i++) 
					wam->Jref->q[i] = CommandSmoother[i].pid_command;
				wam->Jref->q[4] = 0.0; //-.2;
				wam->Jref->q[5] = 0.0; //-.2;
				wam->Jref->q[6] = 0.0; //-.2;

				// Implement hand control
				//ControlHand( );
		}
		
		// Create pulses on digital IO line to synchronize with spike acquisition
		if( !use_step_mode)
		{
			SampleClockPulse = (update_pos)? 1 : 0;
			AlignmentPulse = (alignment_sample)? 1 : 0;
			DigitalOut( SampleClockPulse, AlignmentPulse);
		}


		// Output the circular buffer on command
		if( read_buffer)
		{
			num_points = NumUnreadValuesInCircularBuffer( &(CircularFeedbackBuffer[0][0]));
			FeedbackOutputBuffer.header.num_points = num_points;
			for( v = 0; v < NUM_FEEDBACK_VARS; v++)
			{
			for( i = 0; i < ROBOT_NUM_JOINTS; i++)
			{
				ReadCircularBuffer( &(CircularFeedbackBuffer[v][i]), 
					&(FeedbackOutputBuffer.buf[v*ROBOT_NUM_JOINTS*num_points + i*num_points]));

			}
			}
			clear_flag_bits( WAMcallbackFlag, WC_READ_BUFFER);
		}

		// Output the circular buffer on command
		if( consume_buffer)
		{
			if( read_buffer) syslog( LOG_ERR, "ML: WAMcallback WARNING: read_buffer and consume_buffer flags both set");
			num_points = NumValuesInCircularBuffer( &(CircularFeedbackBuffer[0][0]));
			FeedbackOutputBuffer.header.num_points = num_points;
			for( v = 0; v < NUM_FEEDBACK_VARS; v++)
			{
			for( i = 0; i < ROBOT_NUM_JOINTS; i++)
			{
				ConsumeCircularBuffer( &(CircularFeedbackBuffer[v][i]), 
					&(FeedbackOutputBuffer.buf[v*ROBOT_NUM_JOINTS*num_points + i*num_points]));

			}
			}
			clear_flag_bits( WAMcallbackFlag, WC_CONSUME_BUFFER);
		}

		// Maintain circular buffer of recent values
		if( DoPositionBuffering) 
		{
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_SampleHeader][0]), SampleHeader.SerialNo);
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_SampleHeader][1]), SampleHeader.Flags);
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_SampleHeader][2]), (double) 0.0 / (double) 0.0);
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_SampleHeader][3]), (double) 0.0 / (double) 0.0);
			for( i = 0; i < ROBOT_NUM_JOINTS; i++)
			{
				//the number of variables put here- should be equal to NUM_FEEDBACK_VARS
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_RemoteCmd][i]), rad2deg( CommandSmoother[i].dest));
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_InterpCmd][i]), rad2deg( CommandSmoother[i].desired_path_point));
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_LimitedCmd][i]), rad2deg( CommandSmoother[i].limited_path_point));
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_PIDCommand][i]), rad2deg( CommandSmoother[i].pid_command));
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_EncoderPos][i]), rad2deg( wam->Jpos->q[i]));
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_FBTorque][i]), wam->Jtrq->q[i]);
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_MaxLimits][i]), rad2deg(curJointLimits->max[i]));
				PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_MinLimits][i]), rad2deg(curJointLimits->min[i]));
			}
			/* In order to send correct feedback about the tooltip cartesian end point of the WAM:
			   1) Convert Barrett's Cartesian coordinates -> our coordinate system:
				  X -> Y , Y -> X, Z -> Z
			      our X = q[1] (Barrett's Z), our Y = q[0] (Barrett's X), our Z = q[2] (Barrett's Y)
			   2) Convert from [m] to [mm]
			   3) Transform to our origin: Barrett's origin in at the shoulder, ours is at the monkey's mouth
			      (0,0,0) -> (100, -300, 275)
			   *) Notice the the fourth element has a meaningless value, since the buffer holds 4 values for each var,
			      and we only put 3 valid values in it
			*/
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_CartPos][0]), wam->R6pos->q[0]*1000+X_TRANSFORM_BARRETT_2_ML);
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_CartPos][1]), wam->R6pos->q[2]*1000+Y_TRANSFORM_BARRETT_2_ML);
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_CartPos][2]), wam->R6pos->q[1]*1000+Z_TRANSFORM_BARRETT_2_ML);
			PutInCircularBuffer( &(CircularFeedbackBuffer[FBN_CartPos][3]), (double)GripperRef);
		}
		
	}

   return 0;
}

/*----------------------*
 * Movement- high level *
 *----------------------*/
/*
 * Sets a position to be followed by the regular control method
 * =>YOU MUST SET DoPositionFollowing & DoPositionBuffering before calling this function!
 *
 * - dest must be of size ROBOT_NUM_JOINTS
 * - get_buffer==1 means that all buffers will be sent over the socket
 * 
 * Returns: 1- on success, 0- on failure
 */
int FollowPosition( double *dest, unsigned char gripper, int alignment_flag, int get_buffer, SOCKET_HANDLE sock)
{
	int i;
	int KeepRunning = 1;
	char wc_flags   = 0x00;

	if(get_buffer && (sock == NULL))
		return 0;

	for(i=0; i<ROBOT_NUM_JOINTS; i++)
	{
		JointRef[i]    =  dest[i];
		//syslog(LOG_ERR, "ML: FollowPosition: Joint %d [%f]", i, JointRef[i]);
	}
	GripperRef = gripper;
  
	set_flag_bits( wc_flags, WC_UPDATE_POS);
	if( get_buffer) set_flag_bits( wc_flags, WC_READ_BUFFER);
	if( alignment_flag) set_flag_bits( wc_flags, WC_ALIGNMENT_SAMPLE);
	set_flag_bits( WAMcallbackFlag, wc_flags);

	//send buffer with data from BEFORE movement began
	if( get_buffer) KeepRunning = GetAndSendBuffer( sock, DO_READ);
	
	return KeepRunning;
}

/*
 * Jumps to the desired position using the ramp control method
 * =>YOU MUST SET DoPositionFollowing & DoPositionBuffering before calling this function!
 *
 * - dest must be of size ROBOT_NUM_JOINTS
 * - get_buffer==1 means that all buffers will be sent over the socket twice
 * 
 * Returns: 1 on success, 0 on failure | Returns only when the ramp move is done
 */
int JumpToPosition( double *dest, unsigned char gripper, int get_buffer, SOCKET_HANDLE sock)
{
	int i;
	int KeepRunning = 1;
	char wc_flags   = 0x00;
	int success_buffer_send  = 0;
	int success_jump_command = 1;
	

	//check if a previous jump has timed out
	if(check_flag_bits(WAMcallbackFlag,WC_STEP_MODE_TIMEOUT))
	{
		syslog( LOG_ERR, "ML: JumpToPosition: A previous jump has timed out- ABORTING");
		return 0;
	}

	if(get_buffer && (sock == NULL))
	{
		syslog( LOG_ERR, "ML: JumpToPosition: sock was NULL while get_buffer was TRUE");
		return 0;
	}

	for(i=0; i<ROBOT_NUM_JOINTS; i++)
	{
		JointRef[i]    =  dest[i];
		DisplayInfo.StepMode[i] = 1;
	}
	GripperRef = gripper;
  
	set_flag_bits( wc_flags, WC_UPDATE_POS);
	set_flag_bits( wc_flags, WC_STEP_MODE);
	if( get_buffer) set_flag_bits( wc_flags, WC_READ_BUFFER);
	set_flag_bits( WAMcallbackFlag, wc_flags);

	//send buffer with data from BEFORE step movement began
	if( get_buffer) KeepRunning = GetAndSendBuffer( sock, DO_READ);
	
	//set global NumStepModeLoops
	NumStepModeLoops = MAX_JUMP_TO_POS_LOOPS;
	// Wait for step command to finish
	ResetDebugInfo(); sprintf(DisplayInfo.DebugInfo, "JumpToPosition: waiting for step command to finish");
	while( check_flag_bits( WAMcallbackFlag, WC_STEP_MODE) && !check_flag_bits(WAMcallbackFlag,WC_STEP_MODE_TIMEOUT) ) usleep( 200);
	ResetDebugInfo(); sprintf(DisplayInfo.DebugInfo, "JumpToPosition: step command finished");
	
	//send buffer with step feedback from step movement
	if( get_buffer) 
	{	//returns 1 on success, 0 on failure
		success_buffer_send = AskGetAndSendBuffer( sock, DO_READ);
		if( !success_buffer_send) syslog( LOG_ERR, "ML: JumpToPosition: Failed to send back feedback buffer");
	}

	if( check_flag_bits(WAMcallbackFlag, WC_STEP_MODE_TIMEOUT) )
	{
		success_jump_command = 0;//signal to QUIT if the step
		if( !success_jump_command) syslog( LOG_ERR, "ML: JumpToPosition: Jump command timed out");
	}

	KeepRunning = success_jump_command && success_buffer_send;
	return KeepRunning;
}

// Set joint limits. Jump to a position within limits if current pos out of new limits
void SetLimits( JOINT_LIMITS_STRUCT *newJointLimits)
{
	int i;
	int exceeds_limit;
	double limited_position[ROBOT_NUM_JOINTS];

	// Check if current positon would exceed the new limits
	for( i = 0; i < ROBOT_NUM_JOINTS; i++) limited_position[i] = JointPos[i];
	exceeds_limit = 0;
	for( i = 0; i < ROBOT_NUM_JOINTS; i++) {
		if( JointPos[i] < newJointLimits->min[i]) {
			limited_position[i] = newJointLimits->min[i];
			exceeds_limit = 1;
		}
		if( JointPos[i] > newJointLimits->max[i]) {
			limited_position[i] = newJointLimits->max[i];
			exceeds_limit = 1;
		}
	}

	// If it does exceed the limits then make a jump to nearest position at limit
	if( exceeds_limit) JumpToPosition( limited_position, GRIPPER_NO_CMD, 0, NULL);

	// Set the new limits
	curJointLimits = newJointLimits;
}


/*
 * - Signals WAMcallback to give us the current buffer
 *	 then sends it over the socket.
 * - consume==0: will read buffer, consume==1: will consume buffer
 * - Assumes that the read/consume flags were set before entering the function (!)
 *   Otherwise this function may wait *forever*!!!
 * - Returns: 1 on success, 0 on failure
 */
int GetAndSendBuffer( SOCKET_HANDLE sock, int consume)
{
	int MessageSize, HeaderSize, DataSize;
	int KeepRunning = 1;

	if(consume)
		while( check_flag_bits( WAMcallbackFlag, WC_CONSUME_BUFFER)) usleep( 200);
	else
		while( check_flag_bits( WAMcallbackFlag, WC_READ_BUFFER)) usleep( 200);
	HeaderSize = sizeof(FEEDBACK_HEADER);
	DataSize = FeedbackOutputBuffer.header.num_points 
		     * FeedbackOutputBuffer.header.num_joints 
			 * FeedbackOutputBuffer.header.num_vars 
			 * sizeof(FeedbackOutputBuffer.buf[0]);
	MessageSize = HeaderSize + DataSize;
	if( SendData( sock, (void*) &FeedbackOutputBuffer, MessageSize) < 0) {
		KeepRunning = 0;
		syslog( LOG_ERR, "ML: GetAndSendBuffer: SendData failed");
	}

	return KeepRunning;
}

/*
 * Same as GetAndSendBuffer, but will set the appropriate WAMcallback flags
 * Use this version if this is the only WAMcallback flag that you want to set
 */
int AskGetAndSendBuffer( SOCKET_HANDLE sock, int consume)
{
	//set flags first
	if(consume)
		set_flag_bits( WAMcallbackFlag, WC_CONSUME_BUFFER);
	else
		set_flag_bits( WAMcallbackFlag, WC_READ_BUFFER);

	//get & send buffer
	return GetAndSendBuffer(sock, consume);
}

/*
 * Sends the given event over the socket
 * Returns: 1 on success, 0 on failure
 */
int SendEvent(SOCKET_HANDLE sock, int event_value)
{
	int KeepRunning = 1;
	WAM_EVENT wam_event;

	//initialize event structure
	//wam_event.sample_header = ?;
	wam_event.event_value = event_value;

	if( SendData( sock, (void*) &wam_event, sizeof(wam_event)) < 0) {
		KeepRunning = 0;
		syslog( LOG_ERR, "ML: SendEvent: SendData failed | SendData failed | SendData failed | SendData failed |");
	}

	ResetDebugInfo(); sprintf(DisplayInfo.DebugInfo, "SendEvent: event %d was sent\t\t", event_value);
	return KeepRunning;
}


void MoveToStartingPosition( void)
{
	JumpToPosition( HomeToStartViaPos1, GRIPPER_NO_CMD, 0, NULL);
	//JumpToPosition( HomeToStartViaPos2, GRIPPER_NO_CMD, 0, NULL);
	JumpToPosition( StartTaskPosition, GRIPPER_NO_CMD, 0, NULL);
}

//--------------------------------------------------------------
//globals that will be initialized in ProcessInput()
SOCKET_HANDLE sock, listening_sock;
//--------------------------------------------------------------
void FollowRemotePos( SOCKET_HANDLE sock)
{
	int i, v;
	int KeepRunning=1, status=0;
	int LoopCounter = 0;
	int get_buffer  = 0;
	int step_mode   = 0;
	int alignment_flag = 0;
	int report_jump_complete = 0;
	ROBOT_COMMAND command = {{0,0},-1,0,{J1_SAFE,J2_SAFE,J3_SAFE,J4_SAFE}};
	double RemoteCommand[ROBOT_NUM_JOINTS];
	unsigned char GripperCommand;

	DisplayInfo.FollowRemotePosition = 1;
	syslog(LOG_INFO, "ML: FollowRemotePos: Starting with JointPos = [%.4f,%.4f,%.4f,%.4f]", JointPos[0], JointPos[1], JointPos[2], JointPos[3]);
	
	//initialize command struct with default values
	command.command = WAM_ROBOT_MOVE;
	command.flag = 0;
	for(i=0; i < ROBOT_NUM_JOINTS; i++)
		command.pos[i] = JointPos[i];

	//initialize the variable used to communicate command position to real-time thread
	for( i = 0; i < ROBOT_NUM_JOINTS; i++)
		JointRef[i] = JointPos[i];

	//initialize circular buffers for collecting feedback
	for( v = 0; v < NUM_FEEDBACK_VARS; v++)
		for( i = 0; i < ROBOT_NUM_JOINTS; i++)
			InitializeCircularBuffer( &(CircularFeedbackBuffer[v][i]), MAX_CIRCULAR_BUFFER_SIZE);

	//initialize output buffers that are used for sending back the feedback
	FeedbackOutputBuffer.header.num_points = 0;
	FeedbackOutputBuffer.header.num_joints = ROBOT_NUM_JOINTS;
	FeedbackOutputBuffer.header.num_vars = NUM_FEEDBACK_VARS;
	FeedbackOutputBuffer.header.reserved = 0;

	//initialize global command smoother with current joint position
	for( i = 0; i < ROBOT_NUM_JOINTS; i++)
		InitSmoother(&CommandSmoother[i], JointPos[i], i );

	//initialize SampleHeader
	SampleHeader.SerialNo = 0;
	SampleHeader.Flags = 0;

	//signal WAMcallbackThread to start following positions & start buffering; zero all old flags
	DoPositionFollowing = 1;
	DoPositionBuffering = 1;
	WAMcallbackFlag = 0x00;

	//check that socket was previously open
	if(sock == NULL)
	{
		KeepRunning = 0;
		syslog(LOG_ERR, "ML: FollowRemotePos: sock is NULL!- EXITING");
		ResetDebugInfo(); 
		sprintf(DisplayInfo.DebugInfo, "FollowRemotePos: sock is NULL!- EXITING");
	}else{
		//move to task start position
		MoveToStartingPosition( );
		//send initial position to user
		KeepRunning = AskGetAndSendBuffer( sock, DO_READ);
		//set limits to predefined TASK limits
		SetLimits( &TaskJointLimits);
	}

	while(KeepRunning)
	{
		//ResetDebugInfo(); sprintf(DisplayInfo.DebugInfo, "FollowRemotePos: Recv'ing data...");
		if( RecvData(sock, (void*) &command, sizeof(command)) < 0 ) 
		{
			KeepRunning = 0;
			syslog(LOG_ERR, "ML: FollowRemotePos: RecvData failed");
			ResetDebugInfo(); 
			sprintf(DisplayInfo.DebugInfo, "FollowRemotePos: RecvData failed- EXITING\t\t\t");
			CloseSocket(sock);
			sock == NULL;
			break;
		}
	
		switch(command.command)
		{
		case WAM_ROBOT_QUIT:
			KeepRunning=0;
			DisplayInfo.ClientConnected = 0;
			ResetDebugInfo(); 
			sprintf(DisplayInfo.DebugInfo, "FollowRemotePos: Got WAM_ROBOT_QUIT- EXITING\t\t\t");
			break;

		case WAM_ROBOT_MOVE:
			for(i=0; i<ROBOT_NUM_JOINTS; i++)
			{
				RemoteCommand[i] = deg2rad( command.pos[i]);
				DisplayInfo.CurCommandRad[i] = RemoteCommand[i];
				DisplayInfo.CurCommandDeg[i] = command.pos[i];
			}
		
			// Set flags that control what the WAMcallback Thread does
			get_buffer       = check_flag_bits( command.flag, WAM_CF_READ_BUFFER) ? 1 : 0;
			step_mode        = check_flag_bits( command.flag, WAM_CF_STEP_MODE) ? 1 : 0;
			//alignment_flag   = check_flag_bits( command.sample_header.Flags, SF_ALIGNMENT) ? 1 : 0;
			alignment_flag   = check_flag_bits( command.sample_header.Flags, SF_UNFREEZE) ? 1 : 0;
			report_jump_complete = check_flag_bits( command.flag, WAM_CF_SIGNAL_JUMP_END) ? 1 : 0;
	
			GripperCommand = MapGripperCommand( command.gripper_pos);
				
			if(step_mode)
			{
				SampleHeader.SerialNo = 0;
				SampleHeader.Flags = 0;
				KeepRunning = JumpToPosition( RemoteCommand, GripperCommand, get_buffer, sock);
				if(report_jump_complete) SendEvent(sock, WAM_EVENT_JUMP_COMPLETE);

				if(!KeepRunning)
				{
					ResetDebugInfo();  sprintf(DisplayInfo.DebugInfo, "FollowRemotePos: JumpToPosition failed!");
				}
			}else{
				SampleHeader = command.sample_header;
				KeepRunning = FollowPosition( RemoteCommand, GripperCommand, alignment_flag, get_buffer, sock);
			}
			break;

		case WAM_ROBOT_CONSUME_BUFFER:
			KeepRunning = AskGetAndSendBuffer( sock, DO_CONSUME);
			break;

		case WAM_ROBOT_START_BUFFER:
			DoPositionBuffering = 1;
			break;

		case WAM_ROBOT_STOP_BUFFER:
			DoPositionBuffering = 0;
			break;

		case WAM_SEND_CUR_POS:
			//send current position to the other side
			break;

		default:
			KeepRunning = 0;
			syslog( LOG_ERR, "ML: FollowRemotePos: Received garbage command");
			ResetDebugInfo(); 
			sprintf(DisplayInfo.DebugInfo, "FollowRemotePos: Received garbage command- EXITING");
			break;
		}
	}

	//siganl WAMcallback to stop buffering & position following
	DoPositionBuffering = 0;
	DoPositionFollowing = 0;
	while( DoingPositionFollowing) usleep( 200);//wait for WAMcallback to acknowledge
	
	curJointLimits = &HardJointLimits;
	DisplayInfo.FollowRemotePosition = 0;
}

/*-----------------*
 * Gripper         *
 *-----------------*/

unsigned char MapGripperCommand( double GripperPos)
{
	double Command;
	unsigned char IntegerCommand;
	double Range;
	
	if( GripperPos > 1.0 ) return GRIPPER_CMD_BAD; 
	if( GripperPos < 0.0 ) return GRIPPER_NO_CMD;

	Range = (double) GRIPPER_CMD_MAX - (double) GRIPPER_CMD_MIN;
	// GripperPos is assumed to be in 0..1 range
	Command = (double) GRIPPER_CMD_MIN + GripperPos * Range;
	IntegerCommand = (unsigned char) Command + 0.5; // Round the value
	//IntegerCommand = (IntegerCommand / 2) * 2;
	return IntegerCommand;
}

int IsGripperAlive( void)
{
	int status;
	status = SendCommandToGripper(GRIPPER_CMD_PING);
	return (status == 1) ? 1 : 0;
}

int ShutdownGripper( void)
{
	return SendCommandToGripper(GRIPPER_CMD_SHUTDOWN);
}

int SendCommandToGripper( unsigned char c)
{
	struct {
		unsigned char echo;
		unsigned char status;
	} feedback;
	int nbytes_to_read, nbytes_read;

	DisplayInfo.GripperPos = c;
	if( c == GRIPPER_NO_CMD)
		return 1;	
	
	if( WriteToSerialPort( c) < 1) return -1;
	nbytes_to_read = sizeof( feedback);
	nbytes_read = ReadFromSerialPort( (unsigned char*) &feedback, nbytes_to_read);
	if( nbytes_read < 0) return -2;
	if( nbytes_read < nbytes_to_read) return -3;
	if( feedback.echo != c) return -4;
	switch( feedback.status) {
		case 0:
			return 0;
			break;
		case 1:
			return 1;
			break;
		default:
			return -5;
			break;
	}
}

int ReadFromSerialPort( unsigned char *buffer, int num_bytes)
{
	if( buffer == NULL) return -2;
	return read( (&p)->ifd, buffer, num_bytes);
}

int WriteToSerialPort( unsigned char c)
{
	return write( (&p)->ofd, &c, 1 );
}

////////////////////////////////////////////////////////////////////////////////////
// Digital output from serial port
////////////////////////////////////////////////////////////////////////////////////
#define COM1_BASE 0x3F8
#define COM2_BASE 0x2F8
#define MCR_ADDRESS (COM2_BASE + 4) // Modem control register
#define MCR_DTR 0x01
#define MCR_RTS 0x02
void InitializeDigitalIO( void)
{
	// Enable Serial Port access directly through the IO ports
	//iopl( 3);
	if( ioperm( MCR_ADDRESS, 1, 1)) {
		mvprintw( 20, 0, "Could not set permissions on serial port\n");
	}
}

void DigitalOut( int bit0, int bit1)
{
	unsigned char bit_pattern = 0x00;
	if( bit0) bit_pattern |= MCR_DTR;
	if( bit1) bit_pattern |= MCR_RTS;
	outb( bit_pattern, MCR_ADDRESS);
}

/*-----------------*
 * Main            *
 *-----------------*/
void MyGlobalInit( void)
{
   char chr; 

   InitializeDigitalIO( );   
 
   /* Lead the user through a proper WAM startup */
   mvprintw(1,0,"--------------------------------------------------------------");
   mvprintw(2,0,"|         MOTORLAB WAM CONTROL PROGRAM                       |");
   mvprintw(3,0,"--------------------------------------------------------------");
   mvprintw(5,0,"(*) Turn on WAM");
   mvprintw(6,0,"(*) Switch to IDLE mode");
   mvprintw(7,0," => Press <ENTER> when done");
   mvprintw(8,0," (If you get a seg fault- you probably didn't switch to IDLE...)");
   while((chr=getch())==ERR)
      usleep(5000);
   InitDisplayInfo();

   curJointLimits = &HardJointLimits;   
}

/////////////////////////////////////////////////////////////////////
//
// Entry point for the application.
// Initializes the system and executes the main event loop.
//
/////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
   char    chr,cnt;
   int     err;
   int i;
   struct sched_param mysched;
   char robotName[128];
   
      
   f1 = new_v3();
   j5 = new_btfilter(5);
   j6 = new_btfilter(5);
   j7 = new_btfilter(5);
   init_btfilter_lowpass(j5,0.002,30,0.8);
   init_btfilter_lowpass(j6,0.002,10,0.8);
   init_btfilter_lowpass(j7,0.002,1,0.8);
   syslog_filter(j5);
   syslog_filter(j6);
   syslog_filter(j7);
   /* Figure out what the keys do and print it on screen */
   system("grep \"case '\" wam.c | sed 's/[[:space:]]*case \\(.*\\)/\\1/' > keys.txt");
   read_keys("keys.txt");

   /* Initialize the ncurses screen library */
   init_ncurses();
   atexit((void*)endwin);

   /* Initialize syslog */
   openlog("WAM", LOG_CONS | LOG_NDELAY, LOG_USER);
   atexit((void*)closelog);
   syslog(LOG_ERR,"...Starting btdiag program...");

   /* Initialize the display mutex */
   test_and_log(
      pthread_mutex_init(&(disp_mutex),NULL),
      "Could not initialize mutex for displays.");

   MyGlobalInit( );

#ifndef BTOLDCONFIG

   err = ReadSystemFromConfig("wam.conf");
#else //BTOLDCONFIG
#endif //BTOLDCONFIG
   /* If the robot name was given on the command line, use it */
   *robotName = 0;
   for(i = 1; i < argc-1; i++) {
      if(!strcmp(argv[i],"-n"))
         strcpy(robotName, argv[i+1]);
   }

   /* Do we want to bypass the safety circuit + pendant? */
   NoSafety = 0;
   for(i = 1; i < argc-1; i++) {
      if(!strcmp(argv[i],"-ns"))
         NoSafety = 1;
   }

   /* Initialize and get a handle to the robot */
   if(!(wam = OpenWAM("wam.conf", robotName)))
      exit(1);

   /* Check and handle any additional command line arguments */
   for(i = 1; i < argc-1; i++) {
      if(!strcmp(argv[i],"-g")) // If gimbals are being used
      {
         initGimbals(wam);
         useGimbals = TRUE;
         syslog(LOG_ERR, "Gimbals expected.");
      }
   }

   /* Register the ctrl-c interrupt handler */
   signal(SIGINT, sigint_handler);

   wam->logdivider = 1;
   //syslog(LOG_ERR, "chkpt 1");
   PrepDL(&(wam->log),15);
   //syslog(LOG_ERR, "chkpt 2");
   AddDataDL(&(wam->log),&(wam->log_time),sizeof(double),2,"Time");
   //AddDataDL(&(wam->log),valptr_vn(wam->Jpos),sizeof(btreal)*7,4,"Jpos");
   //AddDataDL(&(wam->log),valptr_vn(wam->Jpos),sizeof(btreal)*7,4,"Jpos");
   AddDataDL(&(wam->log),&(wam->act[0].puck.position),sizeof(long),BTLOG_LONG,"M1pos");
   AddDataDL(&(wam->log),&(wam->act[1].puck.position),sizeof(long),BTLOG_LONG,"M2pos");
   AddDataDL(&(wam->log),&(wam->act[2].puck.position),sizeof(long),BTLOG_LONG,"M3pos");
   AddDataDL(&(wam->log),&(wam->act[3].puck.position),sizeof(long),BTLOG_LONG,"M4pos");
   //AddDataDL(&(wam->log),&(Jpos_filt[4]),sizeof(btreal)*3,4,"Filt");
   //AddDataDL(&(wam->log),&(wamdata[4]),sizeof(btreal)*3,4,"Src");
   //syslog(LOG_ERR, "chkpt 3");
   //AddDataDL(&(wam->log),&(Jpos_filt[4]),sizeof(btreal)*3,4,"Filt");
   InitDL(&(wam->log),1000,"datafile.dat");
   //syslog(LOG_ERR, "chkpt 4");

   /* Set the safety limits */
   setSafetyLimits(2.0, 2.0, 2.0);  // ooh dangerous
   setProperty(0,10,TL2,FALSE,5400); //Eliminate torque faults in silly places
   setProperty(0,10,TL1,FALSE,1800); //Eliminate torque faults in silly places


   /* Prepare MODE */
   jdest = new_vn(len_vn(wam->Jpos));
   cdest = new_vn(len_vn(wam->R6pos));
   wv = new_vn(7);

   active_bts = &(wam->Jsc);
   setmode_bts(active_bts,SCMODE_IDLE);
   active_pos = wam->Jpos;
   active_trq = wam->Jtrq;
   active_dest = jdest;
   prev_mode = SCMODE_IDLE;

   /* Create a new trajectory */
   vt_j = new_vta(len_vn(active_pos),50);
   vta = &vt_j;
   register_vta(active_bts,*vta);

   active_file[0] = 0;

   init_haptics();
   /* Open serial port */
   if(err = serialOpen(&p, "/dev/ttyS0")) {
      syslog(LOG_ERR, "Error opening serial port: %d", err);
   }
   serialSetBaud(&p, 9600);

   // Initialize debugging for hand
   InitializeHandDebugging( );

   /* Spin off the WAM control thread */
   wam_thd.period = WC_SCHEDULING_PERIOD;
   btthread_create(&wam_thd,90,(void*)WAMControlThread,(void*)wam);

   /* Spin off the display thread */
   btthread_create(&disp_thd,0,(void*)DisplayThread,NULL);

   while (!done) {
      /* Check the active trajectory for completion */
      if (get_trjstate_bts(active_bts) == BTTRAJ_DONE && !active_bts->loop_trj) {  // BZ-16Nov2005
         stop_trj_bts(active_bts);
         setmode_bts(active_bts,prev_mode);
      }

      /* Check and handle user keypress */
      if ((chr = getch()) != ERR)
         ProcessInput(chr);
      evalDL(&(wam->log));
      usleep(100000); // Sleep for 0.1s
   }

   btthread_stop(&wam_thd); //Kill WAMControlThread
   syslog_filter(j5);
   CloseDL(&(wam->log));
   DecodeDL("datafile.dat","dat.csv",1);

   // Wrap up hand debugging
   FinishHandDebugging( );
   
   exit(1);
}
int WAMcallback_orig(struct btwam_struct *wam)
{
   int i;
   int nob;
   int cnt;

   static double da;

   wamdata[0]=wam->log_time;
   for(i=0;i<7;i++)
   {
      wamdata[i]=getval_vn(wam->Jpos,i);
   }
   da += 0.001;
   Jpos_filt[4] = eval_btfilter(j5,wamdata[5]);
   Jpos_filt[5] = eval_btfilter(j6,wamdata[5]);
   Jpos_filt[6] = eval_btfilter(j7,wamdata[5]);


   eval_state_btg(&(pstate),wam->Cpos);
   eval_bthaptics(&bth,(vect_n*)wam->Cpos,(vect_n*)pstate.vel,(vect_n*)zero_v3,(vect_n*)wam->Cforce);

   if(zDown)
      set_v3(wam->Cforce, add_v3(wam->Cforce, const_v3(f1,0,0,-1.5)));

   apply_tool_force_bot(&(wam->robot), wam->Cpoint, wam->Cforce, wam->Ctrq);
   return 0;
}
void read_keys(char *filename)
{
   FILE *inf;
   int done = 0;
   int cnt = 0;
   int len = 100;
   int ret;

   num_commands = 0;
   inf = fopen(filename,"r");
   ret = getline(&(command_help[num_commands]),&len,inf);
   if (inf != NULL) {
      while (!done) {
         command_help[num_commands] = (char*)btmalloc(100);
         ret = getline(&(command_help[num_commands]),&len,inf);
         if (ret == -1 || num_commands > 98)
            done = 1;
         else
            command_help[num_commands][ret-1] = 0;
         num_commands++;
      }
   }
   fclose(inf);
   inf = fopen("test.out","w");
   for(cnt = 0;cnt < num_commands;cnt++)
      fprintf(inf,"%s",command_help[cnt]);
   fclose(inf);

}
void init_haptics(void)
{
   int cnt;
   btreal xorig,yorig,zorig;
   int objectCount = 0;

   p1 = new_v3();
   p2 = new_v3();
   p3 = new_v3();
   xorig = 0.0;
   yorig = 0.0;
   zorig = 0.10;

   new_bthaptic_scene(&bth,10);
   init_state_btg(&pstate,0.002,30.0);

   // Create workspace bounding box
   init_bx_btg(&boxs[0],const_v3(p1,0.7,0.0,zorig+0.0),const_v3(p2,0.7,0.01,zorig+0.0),const_v3(p3,0.7,0.0,zorig+0.01),1.0,0.6,0.4,1);
   init_bulletproofwall(&bpwall[0],0.0,0.0,0.05,4000.0,10.0,10.0);
   init_normal_box_bth(&objects[objectCount],&boxs[0],(void*)&bpwall[0],bulletproofwall_nf);
   addobject_bth(&bth,&objects[objectCount++]);

   // Create nested spheres
   init_sp_btg( &spheres[0],const_v3(p1,0.5,0.0,zorig+0.0),const_v3(p2,0.4,0.0,zorig+0.0),0);
   //  init_sp_btg( &spheres[1],const_v3(p1,0.5,0.0,zorig+0.0),const_v3(p2,0.42,0.0,zorig+0.0),1);
   init_sp_btg( &spheres[2],const_v3(p1,0.5,0.0,zorig+0.0),const_v3(p2,0.3,0.0,zorig+0.0),0);
   init_sp_btg( &spheres[3],const_v3(p1,0.5,0.0,zorig+0.0),const_v3(p2,0.32,0.0,zorig+0.0),1);
   init_wickedwall(&wickedwalls[0],500.0, 2.0,0.5,0.1,0.01);
   init_normal_sphere_bth(&objects[objectCount],&spheres[0],(void*)&wickedwalls[0],wickedwall_nf);
   addobject_bth(&bth,&objects[objectCount++]);
   for(cnt = 2;cnt < 4;cnt++) {
      init_wickedwall(&wickedwalls[cnt],3000.0, 10.0,5.0,0.020,0.01);
      init_normal_sphere_bth(&objects[objectCount],&spheres[cnt],(void*)&wickedwalls[cnt],wickedwall_nf);
      addobject_bth(&bth,&objects[objectCount++]);
   }

   const_v3(wam->Cpoint,0.0,-0.0,0.0);

   registerWAMcallback(wam,WAMcallback);

}

/* Initialize the ncurses screen library */
void init_ncurses(void)
{
   initscr();
   cbreak();
   noecho();
   timeout(0);
   clear();
}

/** Traps the Ctrl-C signal.
    Quits the program gracefully when Ctrl-C is hit.
*/
void sigint_handler()
{
   exit(1);
}

/** Spins in a loop, updating the screen.
    Runs as its own thread, updates the screen.
*/
void DisplayThread()
{
   int cnt,err;

   clear();
   refresh();
   while (!done) {
      test_and_log(
         pthread_mutex_lock(&(disp_mutex)),"Display mutex failed");
      switch(screen) {
      case SCREEN_MAIN:
         RenderMAIN_SCREEN();
         break;
      case SCREEN_HELP:
         RenderHELP_SCREEN();
         break;
      }
      pthread_mutex_unlock(&(disp_mutex));
      usleep(100000);
   }

}

/** Locks the display mutex.
    Allows the user to enter on-screen data without fear of display corruption.
*/
void start_entry()
{
   int err;
   test_and_log(
      pthread_mutex_lock(&(disp_mutex)),"Display mutex failed");
   move(entryLine, 1);
   echo();
   timeout(-1);
}

/** Unlocks the display mutex.
    Allows the computer to resume automatically updating the screen.
*/
void finish_entry()
{
   noecho();
   timeout(0);
   move(entryLine, 1);
   addstr("                                                                              ");
   refresh();
   pthread_mutex_unlock( &(disp_mutex) );
}

/** Draw the main information screen.
    Dynamically draw the puck information on the screen.
*/
void RenderMAIN_SCREEN()
{
   int cnt, idx, Mid, cp;
   int line, line2;
   int cpt, nrows;
   double gimb[4],tacc,tvel;
   vectray* vr;
   char vect_buf1[250];
   int itr=0;
   char command_buf[1000]={0};
   char step_mode[1000]={0};

  /***** Display the interface text *****/
   line = 0;

   mvprintw(line, 0, "============================================================================");
   line++;
   mvprintw(line , 0,"%c           Barrett Technology - Diagnostic Application                    %c", 186, 186);
   line++;
   mvprintw(line,  0,"%c            Hacked by Sagi P. &  Meel V., July 2006                       %c", 186, 186);  
   line++;
   mvprintw(line, 0, "============================================================================");
   line+=2;

   // Show MODE
   if (active_bts == &(wam->Jsc)) {
      mvprintw(line, 0, "Mode       : Joint Space    ");
   } else if (active_bts == &(wam->Csc)) {
      mvprintw(line, 0, "Mode       : Cartesian Space");
   } else {
      mvprintw(line, 0, "Mode       : Undefined!!!   ");
   }
   ++line;

   // Show CONSTRAINT
   if (getmode_bts(active_bts)==SCMODE_IDLE)
      mvprintw(line, 0, "Constraint : IDLE      ");
   else if (getmode_bts(active_bts)==SCMODE_POS)
      mvprintw(line, 0, "Constraint : POSITION  ");
   else if (getmode_bts(active_bts)==SCMODE_TRJ)
      mvprintw(line, 0, "Constraint : TRAJECTORY");
   else
      mvprintw(line, 0, "Constraint : UNDEFINED!");
   ++line;

   if (bth.state) {
      mvprintw(line, 0, "Haptics    : ON    ");
   } else {
      mvprintw(line, 0, "Haptics    : OFF    ");
   }
   line+=2;
   
   //MOTORLAB additions
   mvprintw(line, 0, "----------------------------------------------------------------------------");
   line+=2;

   if(!DisplayInfo.ListeningSocketOpen)
   {
      mvprintw(line, 0, "Listening Socket      : CLOSED                               ");
   }else{
      if(DisplayInfo.ClientConnected)
      		mvprintw(line, 0, "Listening Socket      : OPEN  - Client connected      ");
      else
      		mvprintw(line, 0, "Listening Socket      : OPEN  - No clients connected  ");
   }
   line+=2;
   
   if(DisplayInfo.FollowRemotePosition)
   {
      mvprintw(line, 0, "Follow Remote Position: ON    ");
      ++line;
      sprintf(command_buf, "Command Position (deg): "); 
      for(itr=0; itr < ROBOT_NUM_JOINTS; itr++)
	      sprintf(command_buf+strlen(command_buf), "[%f8.4] ", DisplayInfo.CurCommandDeg[itr]);
      mvprintw(line, 0, "%s", command_buf);
      ++line;
      sprintf(command_buf, "Command Position (rad): "); 
      for(itr=0; itr < ROBOT_NUM_JOINTS; itr++)
	      sprintf(command_buf+strlen(command_buf), "[%f8.4] ", DisplayInfo.CurCommandRad[itr]);
      mvprintw(line, 0, "%s", command_buf);
    }else{
      mvprintw(line, 0, "Follow Remote Position: OFF    ");
      ++line;
      mvprintw(line, 0, "Command Position (deg): ");
      ++line;
      mvprintw(line, 0, "Command Position (rad): ");
   }
   ++line;
   mvprintw(line, 0, "MAX_ACC=[%.3f]  |  MAX_VEL=[%.3f]  |  STEP_MAX_ACC=[%.3f]  |  STEP_MAX_VEL=[%.3f]", MAX_ACC, MAX_VEL, STEP_MAX_ACC, STEP_MAX_VEL);
   ++line;
   
   for(itr=0; itr<sizeof(step_mode); itr++) step_mode[itr]=0;
   sprintf(step_mode, "Step Mode             : [ "); 
   for(itr=0; itr < ROBOT_NUM_JOINTS; itr++)
   {
	   if(DisplayInfo.StepMode[itr])
		   sprintf(step_mode+strlen(step_mode), "| ON  ");
	   else
		   sprintf(step_mode+strlen(step_mode), "| OFF ");
   }
   sprintf(step_mode+strlen(step_mode), " | ]");
   mvprintw(line, 0, step_mode);
   //mvprintw(line, 0,    "Step Mode             : [ %d | %d | %d | %d ]", DisplayInfo.StepMode[0], DisplayInfo.StepMode[1], DisplayInfo.StepMode[2], DisplayInfo.StepMode[3]);
   line++;

   mvprintw(line, 0, "Gripper command       : %i\t\t\t", DisplayInfo.GripperPos);
   line+=2;
  	
   if(!DisplayInfo.DebugFlag)
   {
	   mvprintw(line, 0, "DEBUG_INFO:                                                           ");
   }else{
	   //show history
	   mvprintw(line, 0, "DEBUG_INFO:\n%s", DisplayInfo.DebugInfo);
	   //show current debug info
	   line+=2;
	   mvprintw(line, 0, "%s", DisplayInfo.DebugInfo2);
   }
   line+=2; 
   mvprintw(line, 0, "----------------------------------------------------------------------------");
   ++line;

   line+=2;

   // Show TRAJECTORY
   if (cteach)
      mvprintw(line, 0, "Trajectory : Teaching continuous trajectoy");
   else if (*vta == NULL)
      mvprintw(line, 0, "Trajectory : NONE                         ");
   else
      mvprintw(line, 0, "Trajectory : %s                           ",*active_file?active_file:"NONE");
   ++line;
   mvprintw(line, 0, "Velocity   : %+8.4f  ",vel);
   ++line;
   mvprintw(line, 0, "Accel      : %+8.4f  ",acc);
   ++line;
   mvprintw(line, 0, "Destination: %s ",sprint_vn(vect_buf1,active_dest));
   line+=2;

   mvprintw(line, 0, "Position   : %s ", sprint_vn(vect_buf1,active_pos));
   ++line;
   mvprintw(line, 0, "Target     : %s ", sprint_vn(vect_buf1,active_bts->qref));
   ++line;
   mvprintw(line, 0, "Force      : %s ", sprint_vn(vect_buf1,active_trq));
   line+=2;

   if (*vta != NULL) { // print current point
      vr = get_vr_vta(*vta);
      cpt = get_current_idx_vta(*vta);
      nrows = numrows_vr(vr);
      mvprintw(line,0,"Teach Point: %d of %d      ",cpt,nrows-1);
      line++;

      mvprintw(line  , 0 , "Previous   :\t\t\t\t\t\t\t\t\t\t");
      mvprintw(line+1, 0 , "Current    :\t\t\t\t\t\t\t\t\t\t");
      mvprintw(line+2, 0 , "Next       :\t\t\t\t\t\t\t\t\t\t");

      // Previous
      if (nrows > 0 && cpt > 0)
         mvprintw(line, 13,"%s ", sprint_vn(vect_buf1,idx_vr(vr,cpt-1)));

      // Current
      if (nrows > 0) {
         if (nrows != cpt)
            mvprintw(line+1, 13 , "%s ", sprint_vn(vect_buf1,idx_vr(vr,cpt)));
         else
            mvprintw(line+1, 13 , "END OF LIST");
      } else
         mvprintw(line+1, 13 , "EMPTY LIST");

      // Next
      if (nrows > 1)
         if (cpt < nrows-1)
            mvprintw(line+2, 13,"%s ", sprint_vn(vect_buf1,idx_vr(vr,cpt+1)));
         else if (cpt == nrows-1)
            mvprintw(line+2, 13, "END OF LIST");
      line += 3;
   } else {
      line++;
      line++;
      mvprintw(line, 0 ,   "No Playlist loaded. [l] to load one from a file, [n] to create a new one.");
      line += 2;
   }
   /*  line += 1;
     mvprintw(line,0,"bts: state:%d",active_bts->mode);
     mvprintw(line,20,"trj: state:%d",active_bts->btt.state);
     line += 1;
   */   entryLine = line;
   refresh();
}

void RenderHELP_SCREEN()
{
   int cnt, line = 0;

   mvprintw(line, 0, "Help Screen - (press 'h' to toggle)");
   line += 2;
   for (cnt = 0; cnt < num_commands;cnt++) {
      if (cnt % 2) {
         mvprintw(line,40,"%.39s",command_help[cnt]);
         line += 1;
      } else {
         mvprintw(line,0,"%.39s",command_help[cnt]);

      }
   }
   refresh();
}
void clearScreen(void)
{
   btmutex_lock(&(disp_mutex));
   clear();
   btmutex_unlock(&(disp_mutex));
}

/** Process user input.
    Handles the user's keypress, and performs the function desired by the user.
*/
void ProcessInput(int c) //{{{ Takes last keypress and performs appropriate action.
{
   int cnt,elapsed = 0;
   double ftmp,tacc,tvel;
   int dtmp,status;

   char fn[250],chr;
   int ret;
   int done1;
   btreal zPos;
   int i;
   unsigned char gripper_min_val, gripper_max_val;

   switch (c)
   {
   case '4':
      /* Move to high start position */
      setmode_bts(&(wam->Jsc),SCMODE_IDLE);
      setmode_bts(&(wam->Csc),SCMODE_IDLE);
      SetJointSpace(wam);
      active_bts = &(wam->Jsc);
      active_pos = wam->Jpos;
      active_trq = wam->Jtrq;
      active_dest = jdest;
      vta = &vt_j;
      const_vn(active_dest, -0.6820, 0.5862, 0.7456, 2.3497, 0.0, 0.0, 0.0);
      moveparm_bts(active_bts,vel,acc);
      setmode_bts(active_bts,SCMODE_POS);
      prev_mode = getmode_bts(active_bts);
      if (prev_mode != SCMODE_POS)
         setmode_bts(active_bts,SCMODE_POS);
      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");

      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      break;
  case '5':
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\r4FSET DP 2500\r");
      serialWriteString(&p, "\r12FSET DP 6000\r");
      serialWriteString(&p, "\r3FSET DP 8500\r");
      serialWriteString(&p, "\rM\r");
      //   sleep(1);
      // serialReadLine(&p, fn, &cnt, '>', 30000);
      break;

  case '6':
      /* Joint move to deck */
      const_vn(active_dest, -0.70, 1.026, 0.7791, 2.19, 0.0, 0.0, 0.0);

      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");

      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      /* Cartesian hold in X,Y. Drop in Z */
      setmode_bts(&(wam->Jsc),SCMODE_IDLE);
      setmode_bts(&(wam->Csc),SCMODE_IDLE);
      SetCartesianSpace(wam);
      active_bts = &(wam->Csc);
      active_pos = wam->R6pos;
      active_trq = wam->R6force;
      active_dest = cdest;
      vta = &vt_c;
      stop_btPID(&(wam->d_pos_ctl[2]));
      setgains_btPID(&(wam->d_pos_ctl[2]),0,0,0); // Kill the z-axis gains
      start_btPID(&(wam->d_pos_ctl[2]));
      setmode_bts(active_bts,SCMODE_POS);
      zDown = 1;
      usleep(10000);
      //sleep(1);
      /* Slide card out */
      const_vn(active_dest, 0.5247, -0.0794, 0.0, 0,0, 0.0, 0.0, 0.0);
      zPos = getval_v3(wam->Cpos, 2);
      setval_vn(active_dest, 2, zPos);

      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");
      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      /* Lift arm up for hand re-orientation */
      zPos = getval_v3(wam->Cpos, 2);
      setval_vn(active_dest, 2, zPos+0.1);
      zDown = 0;
      setmode_bts(&(wam->Csc),SCMODE_IDLE);
      stop_btPID(&(wam->d_pos_ctl[2]));
      setgains_btPID(&(wam->d_pos_ctl[2]),2000.0, 5.0, 0.0); // Set the z-axis gains
      start_btPID(&(wam->d_pos_ctl[2]));
      setmode_bts(&(wam->Csc),SCMODE_POS);
      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");
      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      break;
  case '7':
      /* Prepare hand for scoop & pick */
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\r3FSET DP 4800\r");
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\r12FSET DP 10800\r");
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\r4FSET DP 0\r");
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\rM\r");
      //   sleep(1);
      break;
  //case '8':
      /* Move down below card */
      setmode_bts(&(wam->Jsc),SCMODE_IDLE);
      setmode_bts(&(wam->Csc),SCMODE_IDLE);
      SetJointSpace(wam);
      active_bts = &(wam->Jsc);
      active_pos = wam->Jpos;
      active_trq = wam->Jtrq;
      active_dest = jdest;
      vta = &vt_j;
      const_vn(active_dest, -0.5309, 0.8837, 0.4544, 2.2215, 0.0, 0.0, 0.0);

      moveparm_bts(active_bts,vel,acc);
      setmode_bts(active_bts,SCMODE_POS);
      prev_mode = getmode_bts(active_bts);
      if (prev_mode != SCMODE_POS)
         setmode_bts(active_bts,SCMODE_POS);

      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");

      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      /* Move in under card */
      const_vn(active_dest, -0.4826, 0.8970, 0.4910, 2.2107, 0.0, 0.0, 0.0);
      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");

      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      /* Lift card up a little */
      const_vn(active_dest, -0.5287, 0.880, 0.5425, 2.2148, 0.0, 0.0, 0.0);
      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");

      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      break;
  case '8':
      /* Grab card */
      serialWriteString(&p, "\r3M 11000\r");
      usleep(250000);

      break;
  case '9':

      /* Lift card off deck */
      const_vn(active_dest, -0.5466, 0.6972, 0.5737, 2.2891, 0.0, 0.0, 0.0);
      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");

      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      /* Reach out with card */
      if(flip) {
         flip = 0;
         const_vn(active_dest, -0.5532, 0.2486, 0.5554, 1.6646, 0.0, 0.0, 0.0);
         if(moveto_bts(active_bts,active_dest))
            syslog(LOG_ERR,"Moveto Aborted");
         while(getmode_bts(active_bts)==SCMODE_TRJ) {
            usleep(10000);
            //sleep(1);
         }
         const_vn(active_dest, 0.5597, 1.6542, -1.4126, 0.8336, 0.0, 0.0, 0.0);
      } else {
         flip = 1;
         const_vn(active_dest, -0.4310, 1.6646, 1.5667, 0.6012, 0.0, 0.0, 0.0);
      }
      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");
      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      /* Drop Card */

      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\r3FSET DP 16000\r");
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\r12FSET DP 9000\r");
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\r4FSET DP 1500\r");
      serialWriteString(&p, "\r");
      usleep(10000);
      serialWriteString(&p, "\rM\r");
      usleep(250000);
      //   sleep(1);
      if(!flip) {
         const_vn(active_dest, -0.5532, 0.2486, 0.5554, 1.6646, 0.0, 0.0, 0.0);
         if(moveto_bts(active_bts,active_dest))
            syslog(LOG_ERR,"Moveto Aborted");
         while(getmode_bts(active_bts)==SCMODE_TRJ) {
            usleep(10000);
            //sleep(1);
         }
      }

      /* Move to high start position */
      const_vn(active_dest, -0.6820, 0.5862, 0.7456, 2.3497, 0.0, 0.0, 0.0);
      if(moveto_bts(active_bts,active_dest))
         syslog(LOG_ERR,"Moveto Aborted");

      while(getmode_bts(active_bts)==SCMODE_TRJ) {
         usleep(10000);
         //sleep(1);
      }
      break;
   case 'x'://eXit
   case  'X'://eXit
	if(listening_sock != NULL)
	{
		CloseSocket(listening_sock);
	      	DisplayInfo.ListeningSocketOpen = 0;
	}
      done = 1;
      break;
   case '!'://Set puck to mode TORQ
      if (NoSafety)
         EnergizeActuators();
      //setProperty(0, 1, MODE, FALSE, 2);
      break;
   case '@'://Set puck to mode IDLE
      if (NoSafety)
         IdleActuators();
      //setProperty(0, 1, MODE, FALSE, 0);
      break;
   case '#'://Data logging on
      DLon(&(wam->log));
      break;
   case '3'://Data logging off
      DLoff(&(wam->log));
      break;
   case 'z'://Send home-position to WAM
      const_vn(wv, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); //gimbals
      DefineWAMpos(wam,wv);
      break;
   case 'g'://Set gravity compensation
      start_entry();
      addstr("Enter scale value for gravity (1.0 = 9.8m/s^2): ");
      refresh();
      scanw("%lf\n",  &tvel);
      SetGravityComp(wam,tvel);
      finish_entry();
      break;
   case '_'://Refresh display
      clearScreen();
      break;
   case '\t'://Toggle jointspace and cartesian space
      destroy_vta(vta); //empty out the data if it was full
      setmode_bts(&(wam->Jsc),SCMODE_IDLE);
      setmode_bts(&(wam->Csc),SCMODE_IDLE);

      if (active_bts == &(wam->Jsc)) { //switch to cartesian space mode.
         SetCartesianSpace(wam);
         active_bts = &(wam->Csc);
         active_pos = wam->R6pos;
         active_trq = wam->R6force;
         active_dest = cdest;
         vta = &vt_c;
      } else {
         SetJointSpace(wam);
         active_bts = &(wam->Jsc);
         active_pos = wam->Jpos;
         active_trq = wam->Jtrq;
         active_dest = jdest;
         vta = &vt_j;
      }
      clearScreen();
      break;
   case 'D'://Haptics on
      bth.state = 1;
      break;
   case 'd'://Haptics off
      bth.state = 0;
      break;
   case 'p'://Turn on/off Constraint
      if (getmode_bts(active_bts)!=SCMODE_IDLE)
         setmode_bts(active_bts,SCMODE_IDLE);
      else
         setmode_bts(active_bts,SCMODE_POS);
      break;

   case '.'://Play loaded trajectory

      if(getmode_bts(active_bts)!=SCMODE_TRJ) {
         moveparm_bts(active_bts,vel,acc);
         active_bts->loop_trj = 0;
         prev_mode = getmode_bts(active_bts);
         if (prev_mode != SCMODE_POS)
            setmode_bts(active_bts,SCMODE_POS);
         start_trj_bts(active_bts);
      } else {
         start_entry();
         addstr("You must stop the running trajectory first!: ");
         refresh();
         sleep(1);
         finish_entry();
      }
      break;

   case 'b'://Simulate loaded trajectory

      sim_vta(*vta,0.002,getval_vn(idx_vr(get_vr_vta(*vta),numrows_vr(get_vr_vta(*vta))-1),0),"sim.csv");
      break;

   case '?'://Loop loaded trajectory

      if(getmode_bts(active_bts)!=SCMODE_TRJ) {
         moveparm_bts(active_bts,vel,acc);
         active_bts->loop_trj = 1;
         prev_mode = getmode_bts(active_bts);
         if (prev_mode != SCMODE_POS)
            setmode_bts(active_bts,SCMODE_POS);
         start_trj_bts(active_bts);
      } else {
         start_entry();
         addstr("You must stop the running trajectory first!: ");
         refresh();
         sleep(1);
         finish_entry();
      }
      break;

   case '/'://Stop loaded trajectory

      stop_trj_bts(active_bts);
      setmode_bts(active_bts,prev_mode);
      active_bts->loop_trj = 0;
      break;
   case 'Y'://Start continuos teach
      if (active_bts == &(wam->Jsc))
         StartContinuousTeach(wam,1,25,"teachpath");
      else
         StartContinuousTeach(wam,0,25,"teachpath");
      cteach = 1;
      break;
   case 'y'://Stop continuos teach
      StopContinuousTeach(wam);
      DecodeDL("teachpath","teach.csv",0);
      cteach = 0;
      stop_trj_bts(active_bts);
      /** \internal \todo sleeps that are necessary might be forgotten. Can we eliminate the need?*/
      usleep(10000); //needed to give the command a chance to work.
      destroy_vta(vta); //empty out the data if it was full
      strcpy(active_file,"teach.csv");
      *vta = read_file_vta(active_file,20);
      register_vta(active_bts,*vta);
      break;
   case 'l'://Load trajectory from file
      if(getmode_bts(active_bts)!=SCMODE_TRJ) {
         start_entry();
         addstr("Enter filename for trajectory: ");
         refresh();
         scanw("%s", active_file);
         destroy_vta(vta); //empty out the data if it was full

         *vta = read_file_vta(active_file,20);
         register_vta(active_bts,*vta);
         finish_entry();
      } else {
         start_entry();
         addstr("You must stop the running trajectory first!: ");
         refresh();
         sleep(1);
         finish_entry();
      }
      break;
   case 'w'://Save trajectory to a file
      if(getmode_bts(active_bts)!=SCMODE_TRJ) {
         start_entry();
         addstr("Enter filename for trajectory: ");
         refresh();
         scanw("%s", fn);
         if (*vta != NULL) {
            write_file_vta(*vta,fn);
            strcpy(active_file,fn);
         }
         finish_entry();
      } else {
         start_entry();
         addstr("You must stop the running trajectory first!: ");
         refresh();
         sleep(1);
         finish_entry();
      }
      break;
   case 'n'://Create a new trajectory
      if(getmode_bts(active_bts)!=SCMODE_TRJ) {
         start_entry();
         addstr("Enter the max number of points that will be in your trajectory: ");
         refresh();
         ret = scanw("%d", &dtmp);
         destroy_vta(vta);

         strcpy(active_file,user_def);
         *vta = new_vta(len_vn(active_pos),dtmp);
         register_vta(active_bts,*vta);
         active_file[0] = 0;
         finish_entry();
      } else {
         start_entry();
         addstr("You must stop the running trajectory first!: ");
         refresh();
         sleep(1);
         finish_entry();
      }
      break;
   case 'M'://Move to a location
      if(getmode_bts(active_bts)!=SCMODE_TRJ) {
         start_entry();
         addstr("Enter comma seperated destination \".2,.4,...\": ");
         refresh();
         getstr( fn);
         strcat(fn,"\n");
         //syslog(LOG_ERR,"Moveto:%s",fn);
         finish_entry();
         fill_vn(active_dest,0.25);
         csvto_vn(active_dest,fn);
         moveparm_bts(active_bts,vel,acc);
         prev_mode = getmode_bts(active_bts);
         if (prev_mode != SCMODE_POS)
            setmode_bts(active_bts,SCMODE_POS);

         if(moveto_bts(active_bts,active_dest))
            syslog(LOG_ERR,"Moveto Aported");

      } else {
         start_entry();
         addstr("You must stop the running trajectory first!: ");
         refresh();
         sleep(1);
         finish_entry();
      }
      break;
      /*'m': Move to the presently selected trajectory point*/

   case '<'://Select next trajectory point
      prev_point_vta(*vta);
      break;
   case '>'://Select previous trajectory point
      next_point_vta(*vta);
      break;
   case '+'://Insert a point in the trajectory
      if(getmode_bts(active_bts)==SCMODE_IDLE) {
         ins_point_vta(*vta,active_pos);
      }
      break;
   case '-'://Remove a point in the trajectory
      if(getmode_bts(active_bts)==SCMODE_IDLE) {
         del_point_vta(*vta);
      }
      break;
   case 's'://Adjust trj times using a velocity
      if(getmode_bts(active_bts)==SCMODE_IDLE) {
         start_entry();
         addstr("Enter trajectory velocity: ");
         refresh();
         ret = scanw("%lf\n", &tvel);
         if(*vta != NULL)
            dist_adjust_vta(*vta,tvel);
         finish_entry();
      }
      break;
   case 'S'://Scale trajectory in time
      if(getmode_bts(active_bts)==SCMODE_IDLE) {
         start_entry();
         addstr("Enter scale factor: ");
         refresh();
         ret = scanw("%lf\n", &tvel);
         if(vta != NULL)
            time_scale_vta(*vta,tvel);
         finish_entry();
      }
      break;
   case 'A'://Set the corner acceleration
      if(getmode_bts(active_bts)==SCMODE_IDLE) {
         start_entry();
         addstr("Enter Corner Acceleration: ");
         refresh();
         ret = scanw("%lf\n", &tacc);
         if(*vta != NULL)
            set_acc_vta(*vta,tacc);
         finish_entry();
      }
      break;
   case 'a'://Set the move acceleration
      if(getmode_bts(active_bts)==SCMODE_IDLE) {
         start_entry();
         addstr("Enter Move Acceleration: ");
         refresh();
         ret = scanw("%lf\n", &acc);
         finish_entry();
      }
      break;
   case 'v'://Set the move velocity
      if(getmode_bts(active_bts)==SCMODE_IDLE) {
         start_entry();
         addstr("Enter Move Velocity: ");
         refresh();
         ret = scanw("%lf\n", &vel);
         finish_entry();
      }
      break;
   case ','://Pause/Unpause trajectory
      status =  movestatus_bts(active_bts);
      if (status == BTTRAJ_PAUSING || status == BTTRAJ_PAUSED)
         unpause_trj_bts(active_bts,2);
      else
         pause_trj_bts(active_bts,2);
      break;
   case 'h'://Toggle Help
      clearScreen();
      screen = !screen;
      break;

   case 27://Handle and discard extended keyboard characters (like arrows)
      if ((chr = getch()) != ERR) {
         if (chr == 91) {
            if ((chr = getch()) != ERR) {
               if (chr == 67) //Right arrow
               {
               } else if (chr == 68) //Left arrow
               {
               } else {
                  while(getch()!=ERR) {
                     // Do nothing
                  }
                  syslog(LOG_ERR,"Caught unknown keyhit 27-91-%d",c);
               }
            }
         } else {
            while(getch()!=ERR) {
               // Do nothing
            }
            syslog(LOG_ERR,"Caught unknown keyhit 27-%d",c);
         }
      }
      break;
   
   case 'P':
      if(DisplayInfo.ListeningSocketOpen == 0)
      {
	      ResetDebugInfo();
	      sprintf(DisplayInfo.DebugInfo, "About to open listening socket...");
	      listening_sock =  OpenListeningSocket("192.168.2.42", 9999);
	      if(listening_sock == NULL)
	      {
		      sprintf(DisplayInfo.DebugInfo, "Failed to open listening socket!");
		      syslog(LOG_ERR, "btdiag: failed to open listening socket");
		      exit( 1);	
	      }
	      DisplayInfo.ListeningSocketOpen = 1;
      }
      ResetDebugInfo(); sprintf(DisplayInfo.DebugInfo, "Waiting for a client to connect...\t\t\t");
      sock = WaitForClient(listening_sock, 1);
      DisplayInfo.ClientConnected = 1; 
      
      setmode_bts(active_bts,SCMODE_IDLE);
      SetJointSpace(wam);
      setmode_bts(active_bts,SCMODE_POS);
      FollowRemotePos( sock);
      usleep(1000);
      if(sock != NULL)
      	CloseSocket( sock);
      DisplayInfo.ClientConnected = 0;
     
     break;
   case 'O':
     setmode_bts(active_bts,SCMODE_IDLE);
     SetJointSpace(wam);
     setmode_bts(active_bts,SCMODE_POS);
     for( i = 0; i < ROBOT_NUM_JOINTS; i++)
     {
	     DisplayInfo.StepMode[i] = 1;
	     InitSmoother(&CommandSmoother[i], JointPos[i] , i);
     }
     DoPositionFollowing = 1;
     JointRef[3] = 2.0; 
     set_flag_bits(WAMcallbackFlag, WC_STEP_MODE | WC_UPDATE_POS);
     while(check_flag_bits(WAMcallbackFlag, WC_STEP_MODE)) usleep(200);
     DoPositionFollowing =0;
     break;
   case 'H':// Move back home 
      moveparm_bts(active_bts,vel,acc);
      prev_mode = getmode_bts(active_bts);
      if (prev_mode != SCMODE_POS)
	      setmode_bts(active_bts,SCMODE_POS);
      /*
      const_vn( active_dest, 
		      HomeToStartViaPos2[0], 
		      HomeToStartViaPos2[1], 
		      HomeToStartViaPos2[2], 
		      HomeToStartViaPos2[3], 
		      0.0, 0.0, 0.0);
      if(moveto_bts(active_bts,active_dest)) {
	      syslog(LOG_ERR,"Moveto Aborted");
	      break;
      }
      usleep( 3000000);
      */
      
      const_vn( active_dest, 
		      HomeToStartViaPos1[0], 
		      HomeToStartViaPos1[1], 
		      HomeToStartViaPos1[2], 
		      HomeToStartViaPos1[3], 
		      0.0, 0.0, 0.0);
      if(moveto_bts(active_bts,active_dest)) {
	      syslog(LOG_ERR,"Moveto Aborted");
	      break;
      }
      usleep( 3000000);
      
      const_vn( active_dest, 
		      HomePosition[0], 
		      HomePosition[1], 
		      HomePosition[2], 
		      HomePosition[3], 
		      0.0, 0.0, 0.0);
      
      if(moveto_bts(active_bts,active_dest)) {
	      syslog(LOG_ERR,"Moveto Aborted");
	      break;
      }
      
     break;
   case 'm':
    /* 
     start_entry();
     addstr("Enter MIN value to send to gripper (0=c, 55=o, 255=shutdown, 200=getval): ");
     refresh();
     scanw("%c\n",  &gripper_min_val); 
     finish_entry();
     sprintf(DisplayInfo.DebugInfo, "Got MIN value of %c",gripper_min_val );
     usleep(500000);
     start_entry();
     addstr("Enter MAX value to send to gripper (0=closed, 55=open, 255=shutdown, 200=getvalue): ");
     refresh();
     scanw("%c\n",  &gripper_max_val);
     finish_entry();
     sprintf(DisplayInfo.DebugInfo, "Got MAX value of %c",gripper_max_val );
     c=gripper_max_val;
     usleep(1000000);
     for(i=gripper_max_val; i >= gripper_min_val; i--)
     {
	     sprintf(DisplayInfo.DebugInfo, "Sending [%i] on serial port", i, c);
	     usleep(5000000);
	     write((&p)->ofd, &c, 1);
	     c--;
     }
    */ 

     i=1;
     sprintf(DisplayInfo.DebugInfo, "Sending commands to serial port       "); 
     unsigned char c=35;
     for(i=0; i<300; i++)
     {
	write((&p)->ofd, &c, 1);
	sprintf(DisplayInfo.DebugInfo, "[%d] Sending on serial port %d            ",i,c);
        //read((&p)->ifd, &DisplayInfo.GripperValue, sizeof(DisplayInfo.GripperValue));
	usleep(30000);
     }
     break;
   case '[': // Open gripper
     {
     ConfigureHand( );
     break; }
   case ']': // Close gripper
     {
     ClearHandFeedbackBuffer( );
    break; }
   case 'G': // Give gripper command
     {
     char input_string[1000];
     
     start_entry();
     addstr("Enter gripper command string: ");
     refresh();
     ret = scanw("%[A-Za-z0-9 ]\n", input_string);
   
     status = ExecuteHandTextCommand( input_string);
     if( status == 0) sprintf( DisplayInfo.DebugInfo, "Gripper command completed");
    
     finish_entry();
 
     break;
     }
   case '\'': // Read serial port
     {
     unsigned char r[2] = {219, 219};
     int num_bytes;
     num_bytes = read( (&p)->ifd, r, 2);
     //read( (&p)->ifd, &r2, 1);
     //sprintf(DisplayInfo.DebugInfo, "received %i, %i    |", r1, r2); 
     sprintf(DisplayInfo.DebugInfo, "received %i bytes: %i, %i          |", num_bytes, r[0], r[1]); 
     break; }
   default:
      while(getch()!=ERR) {
         // Do nothing
      }
      syslog(LOG_ERR,"Caught unknown keyhit %d",c);

      break;
   }
}
