/* Simple CA Client */

#define TIMEOUT 1.0
#define SCA_OK 1
#define SCA_ERR 0
#define MAX_STRING 40

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

/* Function prototypes */
int main(int argc, char **argv);
static int parseCommand(int argc, char **argv);
static void usage(void);

/* Global variables */
int pvSpecified=0;
char name[MAX_STRING];
char value[MAX_STRING];
double timeout=TIMEOUT;

/***************************** main ***********************************/
int main(int argc, char **argv)
{
    int stat;
    chid pCh;

  /* Parse the command line */
    if(parseCommand(argc,argv) != SCA_OK) exit(1);
    if(!pvSpecified) {
	printf("No PV specified\n");
	exit(1);
    }

  /* Initialize */
    stat=ca_context_create(ca_disable_preemptive_callback);
    if(stat != ECA_NORMAL) {
	printf("ca_context_create failed:\n%s\n",ca_message(stat));
	exit(1);
    }
    
  /* Search */
    stat=ca_create_channel(name,NULL,NULL,CA_PRIORITY_DEFAULT,&pCh);
    if(stat != ECA_NORMAL) {
	printf("ca_create_channel failed:\n%s\n",ca_message(stat));
	exit(1);
    }

  /* Process search */
    stat=ca_pend_io(timeout);
    if(stat != ECA_NORMAL) {
	printf("ca_pend_io timed out for search after %g sec\n",
	  timeout);
	exit(1);
    }

  /* Get the value */
    stat=ca_array_get(DBR_STRING,1,pCh,&value);
    if(stat != ECA_NORMAL) {
	printf("ca_array_get:\n%s\n",ca_message(stat));
	exit(1);
    }
    
  /* Process get */
    stat=ca_pend_io(timeout);
    if(stat != ECA_NORMAL) {
	printf("ca_pend_io timed out for get after %g sec\n",
	  timeout);
	exit(1);
    }
    printf("The value of %s is %s\n",name,value);

  /* Clear the channel */
    stat=ca_clear_channel(pCh);
    if(stat != ECA_NORMAL) {
	printf("ca_clear_channel failed:\n%s\n",ca_message(stat));
    }
    
  /* Exit */
    ca_context_destroy();
    return(0);
}

/**************************** parseCommand ********************************/
static int parseCommand(int argc, char **argv)
{
    int i;

    for(i=1; i < argc; i++) {
	if (argv[i][0] == '-') {
	    switch(argv[i][1]) {
	    case 'h':
		usage();
		exit(0);
	    case 't':
		timeout=atof(argv[++i]);
		break;
	    default:
		fprintf(stderr,"\n\nInvalid option: %s\n",argv[i]);
		usage();
		return SCA_ERR;
	    }
	} else {
	    if(!pvSpecified) {
		strncpy(name,argv[i],MAX_STRING);
		name[MAX_STRING-1]='\0';
		pvSpecified=1;
	    } else {
		printf("\n\nInvalid option: %s\n",argv[i]);
		usage();
		return SCA_ERR;
	    }
	}
    }
    return SCA_OK;
}

/**************************** usage ***************************************/
static void usage(void)
{
    printf(
      "\nUsage: simplecaget [Options] pvname\n"
      "  Connects to pvname and gets the value\n"
      "\n"
      "  Options:\n"
      "    -h help      This message\n"
      "    -t float     Timeout in seconds (Default: %g)\n",TIMEOUT);
}
