#include <udposix.h>
#include <errno.h>
#include <time.h>
#include <sys/times.h>
#include <stdio.h>
#include <stdlib.h>
#include <xgks.h>

/* GKS i/o defines */

#define WS_ID  1
#define INDEV  2
#define PET 2
#define TIME_TO_SLEEP	1


    static
WaitForBreak(ws_id)
    Gint            ws_id;
{
    Gchoice         init;
    Gchoicerec      record;
    Glimit          earea;

    earea.xmin = 0.0;
    earea.xmax = 1279.0;
    earea.ymin = 0.0;
    earea.ymax = 1023.0;

    init.status = GC_NOCHOICE;
    init.choice = 0;
    record.pet1.data = NULL;
    ginitchoice(ws_id, 1, &init, 1, &earea, &record);
    gsetchoicemode(ws_id, 1, GREQUEST, GECHO);
    for (; init.status != GC_NONE;)
	greqchoice(ws_id, 1, &init);
}


main()
{
    static Glimit   echo_area = {.0, 1280.0, 0.0, 1024.0};
    Gloc            loc;
    Gpoint          xy[2];
    int		    npts	= 16;

    /* GKS Initialization */

    gopengks(stderr, 0);
    gopenws(WS_ID, (char*)NULL, (char*)NULL);
    gactivatews(WS_ID);

    xy[0].x = 0.5;
    xy[0].y = 0.5;

    loc.transform = 0;

    while (npts-- > 0) {
	Gloc            response;
	Glocrec         r;
	unsigned	remaining_sleep	= TIME_TO_SLEEP;
	struct tms	tms_time;
	clock_t		start_time	= times(&tms_time);

	loc.position.x = xy[0].x;
	loc.position.y = xy[0].y;

	gsetlocmode(WS_ID, INDEV, GREQUEST, GECHO);
	ginitloc(WS_ID, INDEV, &loc, PET, &echo_area, &r);
	gsetlocmode(WS_ID, INDEV, GSAMPLE, GECHO);

	while ((remaining_sleep = sleep(remaining_sleep)) > 0) {
	    clock_t	cur_time	= times(&tms_time);

	    if ((cur_time - start_time) / 60. > TIME_TO_SLEEP)
		break;
	}

	(void) gsampleloc(WS_ID, INDEV, &response);

	xy[1] = response.position;

	gpolyline(2, xy);

	xy[0]	= xy[1];
    }

    /* wait for break*/

    WaitForBreak(WS_ID);

    gdeactivatews(WS_ID);
    gclosews(WS_ID);
    gclosegks();

    return EXIT_SUCCESS;
}
