#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,c1,c2,t;
   FILE *stream;
   char c,buf[80];

   int	NowCount;	      /* The count which is transfering now */
   int	ErrorCode;
   int	i,j,x1,x2,y1,y2,io_base,irq_no,dma_no;
   float  volt;

   printf("\nio base  (in hex format, 220) = "); scanf("%x",&io_base);
   printf("IRQ number (in int format, 15)  = "); scanf("%d",&irq_no);
   printf("DMA number (in int format, 1/3) = "); scanf("%d",&dma_no);
   printf("(100K --> C1=4) --> C1= "); scanf("%d",&c1);
   printf("(100K --> C2=5) --> C2= "); scanf("%d",&c2);
   A826_Initialize(0,io_base,dma_no,irq_no);
   A826_AD_SetChGainMode(0,A826_BI_1,DMA_MODE);

   init();
   for(;;) {
        _clearscreen(_GCLEARSCREEN);

	sprintf(buf,"C1=%d C2=%d --> Sampling Rate=%5.1fK",c1,c2,2000.0/(float)(c1*c2));
        _settextposition(1,1);
        _outtext(buf);
	sprintf(buf,"Press Any Key Twice To Stop");
        _settextposition(2,1);
        _outtext(buf);

	for(i=0;i<DesireCount;i++) Buffer[i]=0;
	if( A826_AD_DMA_Start(Buffer,DesireCount,c1,c2)!=0 ) {
	    putch(0x07);
	    printf("A826_AD_DMA_Start() error !!! press any key\n");
            getch();
	    goto ret_label;
	}

	while(A826_AD_DMA_Status()) {
	     if(kbhit()) break;
	};
	A826_AD_DMA_Stop( );

	for(i=0; i<16;	i++) {
	   volt=(float)(Buffer[i])*10.0/32768.0;
	   sprintf(buf,"DMA     : [%02d] --> [%03xH]=%+5.3f Volt",i,Buffer[i],volt);
	   _settextposition(i+4,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();
            break;
        }
   }
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() )
        ;
}

