/**********************************************************************************
 * FILE: 	digital_out.c 
 * BASED ON:	sample program from ICS ADVENT PCI-DIO96 Documentation
 * Description: this writes to the digital channels. 
 * 
*********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <asm/io.h>

#ifdef __GLIBC__
	#include <sys/perm.h>
#endif

#define PORT_FILE "/dev/port"

#define BASEADDRESS	0xe000
enum GROUPCHOICE {group0, group1, group2, group3}; 
enum PORTCHOICE {portA, portB, portC};

void writeDigitalChannel(int group, int port, unsigned char channel)
{
	unsigned int PortA;
	unsigned int PortB;
	unsigned int PortC;
	unsigned int PortControl;

	unsigned int writePort;

	unsigned char b, inByte;
	static int fd = -1;
	unsigned char current[3];	

	switch (group) {
		case group0:
			PortA = BASEADDRESS;
			break;
		case group1:
			PortA = BASEADDRESS + 4;
			printf("right group selected\n");
			break;
		case group2:
			PortA = BASEADDRESS + 8;
			break;
		case group3:
			PortA = BASEADDRESS + 12;
			break;
	}

	PortB = PortA + 1;
	PortC = PortA + 2;
	PortControl = PortA + 3;

	switch (port) {
		case portA:
			writePort = PortA;
			break;
		case portB:
			writePort = PortB;
			break;
		case portC:
			writePort = PortC;
			break;
	}	



	printf(" Port A Adress: \t%X in hex.\n", PortA);
	printf(" writing to port: \t%X in hex.\n", writePort);
	printf(" writing to control byte: \t%X in hex.\n", PortControl);
        printf(" channel to select: \t%X in hex.\n", channel); 

	if (fd < 0)
		fd = open(PORT_FILE, O_RDWR);
	if (fd < 0) {
		printf("error opening IOPort file\n");
		return;
	}


	//outportb(writePort, b);
	b = channel;
	lseek(fd, writePort, SEEK_SET);
	if (write(fd, &b, 1) > 0)
		printf("channel turned on sucessfully.\n");

}


bool writeControlPort(int group)
{
	unsigned int PortA;
	unsigned int PortB;
	unsigned int PortC;
	unsigned int PortControl;

	unsigned int writePort;

	unsigned char b, inByte;
	static int fd = -1;
	unsigned char current[3];	

	switch (group) {
		case group0:
			PortA = BASEADDRESS;
			break;
		case group1:
			PortA = BASEADDRESS + 4;
			printf("right group selected\n");
			break;
		case group2:
			PortA = BASEADDRESS + 8;
			break;
		case group3:
			PortA = BASEADDRESS + 12;
			break;
	}

	PortB = PortA + 1;
	PortC = PortA + 2;
	PortControl = PortA + 3;


	if (fd < 0)
		fd = open(PORT_FILE, O_RDWR);
	if (fd < 0) {
		printf("error opening IOPort file\n");
		return false;
	}

	//outportb(PortControl, 0x80);	/* send control byte */
	b = 0x80;
	lseek(fd, PortControl, SEEK_SET);
	if (write(fd, &b, 1) > 0) {
		printf("written control byte successfully\n"); 	
		return true;
	}

	return false;

}
