#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/io.h>
#include <sys/mman.h>
#include <dirent.h>
#include <ctype.h>
#include <malloc.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>
#include <linux/pci.h>
#include <sys/time.h>


#define DATA_REG 0x62
#define CST_REG  0x66

typedef unsigned short u16;
typedef unsigned char u8;

static void ecr_set(u8 addr, u8 value)
{
	while (inb(CST_REG) & 3) usleep(1);
	outb(0x81, CST_REG);
	while (inb(CST_REG) & 2) usleep(1);
	outb(addr, DATA_REG);
	while (inb(CST_REG) & 2) usleep(1);
	outb(value, DATA_REG);
	while (inb(CST_REG) & 2) usleep(1);
}

static u8 ecr_get(u8 addr)
{
	while (inb(CST_REG) & 3) usleep(1);
	outb(0x80, CST_REG);
	while (inb(CST_REG) & 2) usleep(1);
	outb(addr, DATA_REG);
	while (inb(CST_REG) & 2) usleep(1);
	return inb(DATA_REG);
}

static u16 ecr_get16(u8 addr)
{
	return ecr_get(addr) | (ecr_get(addr+1)<<8);
}


int main(int argc, char *argv[])
{
	u16 v1, v2, v3;

	iopl(3);

	v1 = ecr_get16(0xa2);
	v2 = ecr_get16(0xb0);
	v3 = ecr_get16(0x81);

	printf("Battery %d/%d %.2f%% %s %s %s\n",
	       v1, v2, 100.0*v1/(double)v2, v3&0x4?"AC":"", v3&1?"BAT1":"", v3&2?"BAT2":"");

#if 0
	printf("B1RC %d\n", ecr_get16(0xa0));
	printf("B1AB %d\n", ecr_get16(0xa2));
	printf("B1RT %d\n", ecr_get16(0xa4));
	printf("B1VO %d\n", ecr_get16(0xa6));
	printf("B1DC %d\n", ecr_get16(0xb0));
	printf("B1LF %d\n", ecr_get16(0xb2));
	printf("B1DV %d\n", ecr_get16(0xb4));
	printf("B1DL %d\n", ecr_get16(0xb6));
	printf("A1TP %d\n", ecr_get16(0xc0));
	printf("A1AT %d\n", ecr_get16(0xc2));
	printf("A1PT %d\n", ecr_get16(0xc4));
	printf("A1CT %d\n", ecr_get16(0xc6));
	printf("A2TP %d\n", ecr_get16(0xc8));
	printf("A2AT %d\n", ecr_get16(0xca));
	printf("A2PT %d\n", ecr_get16(0xcc));
	printf("A2CT %d\n", ecr_get16(0xce));
#endif

	return 0;
}
