/*
 * Set RTSI_Clock_Mode bitfield
 *
 * Requirements:  A board with RTSI subdevice support.
 *
 * Usage:  clkmode [OPTIONS] VALUE
 *
 * OPTIONS are standard comedilib/demo options.
 *
 * If VALUE < 50, clock mode will be (VALUE % 3) and timebase period will
 * be 50 ns.  Otherwise, clock mode will be 2 (slave mode) and timebase
 * period will be VALUE nanoseconds.
 *
 * Example:  To use a 10 MHz external timebase supplied to the RTSI_OSC pin
 * of /dev/comed1, use...
 *
 * clkmode -f /dev/comedi1 100
 *
 */

#include <stdio.h>
#include <comedilib.h>
#include "examples.h"

int main(int argc, char *argv[])
{
	comedi_t *device;
	int stype;
	comedi_insn insn;
	lsampl_t data[3];
	lsampl_t mode;
	lsampl_t ns;
	int ret;

	// Default subdevice to 10
	subdevice = 10;
	parse_options(argc,argv);

	device=comedi_open(filename);
	if(!device){
		comedi_perror(filename);
		return 1;
	}

	stype = comedi_get_subdevice_type(device,subdevice);
	if(stype!=COMEDI_SUBD_DIO){
		printf("%d is not a digital I/O subdevice\n",subdevice);
		return 2;
	}

	memset(&insn,0,sizeof(insn));

	insn.insn = INSN_CONFIG;
	insn.data = data;
	insn.subdev = subdevice;

	data[0]=INSN_CONFIG_SET_RTSI_CLOCK_MODE;

	// If value is less than 50, assume it is the clock mode, otherwise
	// assume that slave mode is being set and value is the external
	// timebase period.
	if(value < 50) {
		insn.n = 2;
		mode = value & 3;
		ns = 50; // Unused, don't care
	} else {
		insn.n = 3;
		mode = COMEDI_RTSI_CLOCK_MODE_SLAVE;
		ns = value;
	}

	data[1] = mode;
	data[2] = ns;

	ret = comedi_do_insn(device,&insn);

	if(ret<0) {
		comedi_perror(argv[0]);
		printf("Error setting RTSI_Clock_Mode of %s (subdevice %d) to %d", filename, subdevice, mode);
		ret = 3;
	} else {
		printf("RTSI_Clock_Mode of %s is now %d", filename, mode);
		ret = 0;
	}

	printf(" (%d ns)\n", ns);

	comedi_close(device);

	return ret;
}


