#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <dos.h>
#include <conio.h>
#include <string.h>
#include <graph.h>
#include<time.h>
#include "A826.h"

#define WHITE     15
#define GREEN      2
#define RED        4
#define LIGHTGRAY  7

int ZERO;
int Yrange;

void init(void);
void delay( clock_t wait );
int Buffer[2000];
int DesireCount=2000;  /* The count which We desire to transfer */
int MaxX,MaxY;
int incidx;

main()
{
int key,t;
FILE *stream;
char c,buf[80];

   int	DesireCount=2000;     /* The count which We desire to transfer */
   int	i,j,x1,x2,y1,y2,io_base;
   float  volt;

   init();
   printf("\nio base (in hex format) ="); scanf("%x",&io_base);
   A826_Initialize(0,io_base,-1,-1);
   A826_AD_SetChGainMode(0,A826_BI_1,POLLING_MODE);

   for(;;)
	{
        _clearscreen(_GCLEARSCREEN);

	sprintf(buf,"Press Any Key Twice To Stop");
        _settextposition(1,1);
        _outtext(buf);


	A826_AD_PollingArray(Buffer,DesireCount);

        _setcolor(WHITE);
	for(i=0; i<16;	i++) {
	   volt=(float)(Buffer[i])*10.0/32768.0;
	   sprintf(buf,"Polling : [%02d] --> [%03xH]=%+5.3f Volt",i,Buffer[i],volt);
	   _settextposition(i+3,1);
           _outtext(buf);
	}

        _setcolor(GREEN);
	_rectangle(_GBORDER,0,ZERO-Yrange,MaxX,ZERO+Yrange);
        _moveto(0,ZERO);
        _lineto(MaxX,ZERO);
	x1=1;
	y1=ZERO-(float)Buffer[0]*Yrange/32768.0;
	for(i=incidx; i<DesireCount && x1<MaxX ;  i+=incidx){
	    y2=ZERO-(float)Buffer[i]*Yrange/32768.0;
            _setcolor(WHITE);
            _moveto(x1,y1);
            _lineto(x1+1,y2);
            _setcolor(RED);
  	    _setpixel(x1,y1);
	    x1++; y1=y2;
	}
	delay(1000);
	if (kbhit()!=0) {getch(); goto ret_label;}
	}
ret_label:
	getch();
        _setvideomode(_DEFAULTMODE);
}

/* -------------------------------------------------------------------- */
void init(void)
{
  struct videoconfig v;

    _setvideomode(_MAXRESMODE);
    _settextcolor(LIGHTGRAY);

    _getvideoconfig(&v);
    MaxX=v.numxpixels-1;
    MaxY=v.numypixels-1;
    incidx=DesireCount/(MaxX-1);
    Yrange=MaxY/2;
    ZERO=MaxY/2;

}

void delay( clock_t wait )
{
    clock_t goal;

    goal = wait + clock();
    while( goal >= clock() )
        ;
}
