#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>

#include "cxdrv.h"

/* simple test for select */
#define NODE "/dev/cxg0"
#define BUFSIZE 1024*64

char buf[BUFSIZE];

int main(int argc, char **argv)
{
  unsigned long step,next;
  char *prgname=argv[0];
  char node[32];
  int fd;
  int i;
  struct timeval to;
  struct timeval date;
  fd_set selSet;
  FILE *fout=NULL;
  char fname[64]="\0";
  int fnamelen=0;
  int fieldcount=0;

  strcpy(node,NODE);

  if (argc>3 && !strcmp(argv[1],"-f"))
    {
    strcpy(fname,argv[2]);
    strcat(fname,".");
    fnamelen=strlen(fname);
    argv+=2; argc-=2;
    }

  if (argc==4)
    strcpy(node,argv[1]),argv++,argc--;

  if (argc!=3)
    {
    fprintf(stderr,"%s: need two args: step and next\n",prgname);
    exit(1);
    }
  step=atoi(argv[1]);
  next=atoi(argv[2]);

  printf("file %s, step %li, next %li\n",node,step,next);
  fd=open(node,O_RDWR);
  if (fd<0) {perror(node); exit(1);}

  if (Cxg_Interval(fd,step,next)<0) {perror("ioctl()"); exit(1);}

  while (1)
    {
    gettimeofday(&date,NULL);
    printf("reading     at %10d:%06d\n",date.tv_sec,date.tv_usec);
    i=read(fd,buf,BUFSIZE);
    gettimeofday(&date,NULL);
    printf("read %6i at %10d:%06d\n",i,date.tv_sec,date.tv_usec);
    if (fnamelen)
      {
      sprintf(fname+fnamelen,"%03d",fieldcount);
      fout=fopen(fname,"w");
      if (fout) fwrite(buf,1,BUFSIZE,fout);
      fclose(fout);
      fieldcount++;
      }
    to.tv_sec=10; to.tv_usec=0;
    FD_ZERO(&selSet);
    FD_SET(fd,&selSet);
    printf("select()ing...\n");
    i=select(fd+1,&selSet,NULL,NULL,&to);
    printf("%i - left %d:%06d\n",i,to.tv_sec,to.tv_usec);
    }
    
  return 0;
}
