#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <alloc.h>
#include <dos.h>
#include <conio.h>
#include <string.h>
#include <graphics.h>
#include "A823.h"

#define ZERO 204

int   Buffer[2000];

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

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

   init();
   printf("\nio base  (in hex format, 220) = "); scanf("%x",&io_base);
   printf("IRQ number (in int format, 15)  = "); scanf("%d",&irq_no);
   printf("(100K --> C2=20) --> C2= "); scanf("%d",&c2);
   A823_Initialize(0,io_base,-1,irq_no);
   A823_AD_SetChGainMode(0,A823_BI_1,INTERRUPT_MODE);

   for(;;)
	{
	cleardevice();

	sprintf(buf,"C2=%d --> Sampling Rate=%5.1fK",c2,2000.0/(float)(c2));
	outtextxy(5,5,buf);
	sprintf(buf,"Press Any Key Twice To Stop");
	outtextxy(5,5+10,buf);

	if( A823_AD_INT_Start(Buffer,DesireCount,c2)!=0 )
	    {
	    putch(0x07);
	    printf("A823_AD_INT_Start() error !!!\n");
	    exit(1);
	    }

	do
	    {
	    NowCount=A823_AD_INT_Count();
	    if (kbhit()!=0) {getch(); A823_AD_INT_Stop(); goto ret_label;}
	    }while( NowCount<DesireCount );
	A823_AD_INT_Stop( );

	x1=1*5;
	j=Buffer[1]&0x0fff;
	y1=j>>5;
	y1+=ZERO;
	for(i=2; i<127;  i++)
		{
		j=Buffer[i]&0x0fff;
		j=j>>5;
		j+=ZERO;
		x2=i*5; y2=j;
		line(x1,y1,x2,y2);
		x1=x2; y1=y2;
	}

	for(i=1; i<127;  i++)
		{
		j=Buffer[i]&0x0fff;
		j=j>>5;
		j+=ZERO;
		putpixel(i*5,j,RED);
		putpixel(i*5,j+1,RED);
		putpixel(i*5+1,j,RED);
		putpixel(i*5+1,j+1,RED);
		}

	j=ZERO+64;
	for (i=0; i<639; i++)  putpixel(i,j,GREEN);
	for (i=0; i<639; i++)  putpixel(i,j-65,GREEN);
	for (i=0; i<639; i++)  putpixel(i,j+65,GREEN);
	for (j=ZERO-65; j<ZERO+65; j++) putpixel(0,j+64,GREEN);
	for (j=ZERO-65; j<ZERO+65; j++) putpixel(639,j+64,GREEN);

	for(i=0; i<16;	i++)
	{
	Buffer[i]=Buffer[i]&0x0fff;
	volt=(float)(Buffer[i]-2048)/2048.0*5.0;
	sprintf(buf,"Interrupt : [%02d] --> [%03xH]=%+5.3f Volt",i,Buffer[i],volt);
	outtextxy(5,5+10*(i+3),buf);
	}

	delay(1000);
	if (kbhit()!=0) {getch(); goto ret_label;}
	}
ret_label:
	getch();
	cleardevice();
	closegraph();
	}

/* -------------------------------------------------------------------- */

init()
{
int driver,mode,char_size;

driver=EGA;
mode=EGAHI;
initgraph(&driver,&mode,"");
setactivepage(0);
setvisualpage(0);
setcolor(15);
setbkcolor(0);
settextstyle(SMALL_FONT,HORIZ_DIR,6);
}

