// read_encoder_i9093.c : Defines the entry point for the console application.
//

#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "msw.h"
#include "i8093W.h"


int main(int argc, char **argv)
{
	unsigned char  c;
	char ModeStr[5][32]={"Stop","CW/CCW","Pulse/Dir","AB Phase"};
	int i, slot=1, ch=0, enableComparedTrig=0, encoderMode =0, RetValue, ret, dir;
	long encoderValue = 0;
	unsigned long nextPosition=0, firstPosition =0, distance=0;


  RetValue = Open_Slot(slot);
  if (RetValue >0) {
		    printf("Open Slot %d failed!\n",slot);
		    return FAILURE;
	}else {
        ret = i9093_Init(slot);
        if (ret==0)
           printf("\nThere is a I-9093 located at Slot %d\n",slot);
        else {
           printf("There is no I-9093 located at LinPAC.\n");
           return FAILURE;
        }       
  }  

	
	printf("Input Encoder Mode  \n");
	for(i=0;i<4;i++)
  {
    	printf ("\n\t Select %d : %s",i,ModeStr[i]);
  }
  printf("\n");
	scanf("%d", &encoderMode);

	for(ch=0;ch<3;ch++)
	{
		i9093_SetMode(slot, ch, encoderMode);
	}

	// configure compare trigger 
	printf("Input 0 to disable compared trigger function\n");
	printf("Input 1 to enable compared trigger function\n");
	scanf("%d", &enableComparedTrig);
	for(ch=0;ch<3;ch++)
	{
		i9093_ConfigTriggerOut(slot, ch, enableComparedTrig);
	}

	if(enableComparedTrig==1)
	{
		printf("Input first trigger position: ");
		scanf("%ld", &firstPosition);
		printf("\n");
		
		printf("Input trigger distance: ");
		scanf("%ld", &distance);
		printf("\n");
    for(ch=0;ch<3;ch++)
		{
			i9093_SetFirstTrigPosition(slot, ch, firstPosition);
			i9093_SetTrigDistance(slot, ch, dir, distance);
		}
	}

	for(ch=0;ch<3;ch++)
	{
		i9093_ResetEncoder(slot, ch);
	}
	
	
again:

	printf("Encoder Value =>[ ");
	for(ch=0;ch<3;ch++)
	{			
			i9093_Read32BitEncoder(slot, ch, &encoderValue);				
			printf("%ld \t ",encoderValue);
	}
	printf("]\n");


	if(enableComparedTrig==1)
	{
			printf("Next Position =>[ ");
			for(ch=0;ch<3;ch++)
	  	{			
				i9093_ReadNextPosition(slot, ch, &nextPosition);
				printf("%ld \t", nextPosition);
			}
			printf("]\n");
	}			
	
		
	printf("\n\1) Input '0' to reset encoder \n");	
	printf("2) Input 'q' or 'Q' to exit program\n");
	printf("3) Input others to read encoder again \n");

	scanf("%s",&c);  //reset encoder 
	if(c=='0')
	{
		for(ch=0;ch<3;ch++)
		{
			i9093_ResetEncoder(slot, ch);

			if(enableComparedTrig==1)
			{
				i9093_ClearNextPosition(slot, ch);
			}
		}
		goto again;
	}
	else if(c=='q' || c=='Q')  //exit program
	{
		goto end;
	}
	else   //read encoder again
	{
		goto again;
	}
	
end:
  Close_Slot(slot);
	return 0;

}
