/*
 * Copyright 2008 Mike Baker <mbm@openwrt.org>
 * 
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; either version 2 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/io.h>

#define IOBASE_DEFAULT			(0x381)

unsigned short iobase = IOBASE_DEFAULT;

enum { // GPIO OFFSETS
	OutputFunctionSelect	= 0xFC00,
	OutputEnable		= 0xFC10,
	DataOutput		= 0xFC20,
	InputStatus		= 0xFC30,
	PullUp			= 0xFC40,
	OpenDrain		= 0xFC50,
	InputEnable		= 0xFC60,
	Misc			= 0xFC70,

	// GPIO INTERRUPTS
	EventEnable		= 0xFF30,
	PendingFlag		= 0xFF40,
	PolaritySelection	= 0xFF50,
	EdgeLevel		= 0xFF60,

};

void setecindex(unsigned short index)
{
	unsigned char hi = index>>8;
	unsigned char lo = index;

	outb(hi, iobase);
	outb(lo, iobase+1);
}

unsigned char readecdata(unsigned short index)
{
	unsigned char data;
	setecindex(index);
	data = inb(iobase+2);
	return data;
}

void writeecdata(unsigned short index, unsigned char data)
{
	setecindex(index);
	outb(data, iobase+2);
}

void setecdata(unsigned short index, unsigned char mask, unsigned char data)
{
	unsigned char val;
	val = readecdata(index);
	val &= mask;
	val |= data;
	writeecdata(index, val);
}

unsigned char gpiooffset(unsigned char gpio)
{
	return (gpio/8);
}

unsigned char gpiomask(unsigned char gpio)
{
	return (1<<(gpio%8));
}

void setgpio(unsigned char gpio, unsigned char val)
{
	unsigned short index = DataOutput + gpiooffset(gpio);
	unsigned char mask = gpiomask(gpio);
	val = (!!val) * mask; 
	setecdata(index, ~mask, val);
}

int main(int argc, char **argv)
{
	unsigned char val;

	if (iopl(3) < 0){
		perror("iop(3)");
		exit(1);
	}

	setgpio(82, 0);
	// first number is the gpio, second number is the DataOutput value
	// in this example, 82 is the charge led
	// setting the DO to 0 turns on the led

	return 0;
}
