/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 1991 by Mike Parker.				    *
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

/* Diagnostic program that tries to determine what the actual rate
   is of the RCI system clock.

   The problems which this program was written to look for are
   unlikely to occur now that the clock rate is returned by
   an ioctl() on the clock device itself. We will keep the program
   around for while, however, for good luck :-) 
 */

#if !defined(VXWORKS_CFG)

#include <math.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/file.h>
#include <sys/resource.h>

#include "../h/rci.h"

#include "rateTest.h"

extern int running;
extern int pvbuf[SZ+1];
extern int pvx;
extern int ucounter;
extern int lastu;
extern int startupfxn();
extern int controlfxn();
extern int releasefxn();

int rate;

main(ac,av)
int ac;
char **av;
{
 RCI_DESC *td;
 int i;
 double m;
 double dvsq;
 double sd;
 double pct;
 int nzn;
 double nzm;
 double nzdvsq;
 double nzsd;
 double nzpct;
 int max;

 rate = 20;
 if (ac > 1)
  { rate = atoi(av[1]);
    ac --;
    av ++;
  }
 running = 1;
 rciSetOptions(EXIT_ON_ERROR);
  { int nlfd;
    int svfd;
    fflush(stdout);
    nlfd = open("/dev/null",O_RDWR,0);
    svfd = dup(1);
    if (nlfd != 1)
     { dup2(nlfd,1);
       close(nlfd);
     }
    td = rciCreate("foo",0);
    fflush(stdout);
    dup2(svfd,1);
    close(svfd);
  }
 rciScheduling(td,ON_CLOCK,0);
 rciRate(td,rate,0);
 rciControlFxns(td,startupfxn,controlfxn,releasefxn,0);
 i = getpriority(PRIO_PROCESS,0);
 setpriority(PRIO_PROCESS,0,-20);
 pvx = 0;
 rciStart(~0);
 while (running)
  { ucounter ++;
  }
 rciRelease(~0);
 setpriority(PRIO_PROCESS,0,i);
 max = 0;
 m = 0;
 nzm = 0;
 nzn = 0;
 for (i=1;i<=SZ;i++)
  { m += pvbuf[i];
    if (pvbuf[i] != 0)
     { nzm += pvbuf[i];
       nzn ++;
     }
    if (pvbuf[i] > max) max = pvbuf[i];
  }
 m /= SZ;
 if (m == 0)
  { printf("All data points zero -- help!\n");
    exit(0);
  }
 nzm /= nzn;
 dvsq = 0;
 nzdvsq = 0;
 for (i=1;i<=SZ;i++)
  { dvsq += (m-pvbuf[i]) * (m-pvbuf[i]);
    if (pvbuf[i] != 0)
     { nzdvsq += (nzm-pvbuf[i]) * (nzm-pvbuf[i]);
     }
  }
 sd = sqrt(dvsq/SZ);
 nzsd = sqrt(nzdvsq/nzn);
 pct = (sd * 100) / m;
 nzpct = (nzsd * 100) / nzm;
 printf("Mean = %g, sd = %g (%g%% of mean)\n",m,sd,pct);
 if (nzpct >= 10)
  { printf("DATA SAMPLE SUSPECT - is system load high?\n");
  }
 printf("Raw data:");
 for (i=1;i<=SZ;i++)
  { if ((i-1)%8 == 0) putchar('\n');
    printf("%8d",pvbuf[i]);
  }
 putchar('\n');
}

#endif /* !defined(VXWORKS_CFG) */
