#include <stdio.h>
#include <fcntl.h>

#define BIT(bits) ((value) & (bits) ? "1":"0")

#define OUTPUT \
	value=value | extra /*| 64*/; \
	printf("-----: 0x%04x %s %s %s %s:%s %s %s %s\n",value,BIT(128),BIT(64),BIT(32),BIT(16),BIT(8),BIT(4),BIT(2),BIT(1)); \
	sprintf(buf,"%u\n",value); \
	printf("%u\n",value); \
	write(fd,buf,strlen(buf)); \
	usleep(1);

#define WriteCommByte(num,flag) { \
	char buf[256]; \
	unsigned char newnum= (unsigned char)num; \
	unsigned int value,extra; \
	value=num ;\
	printf("Sending 0x%02x (%d) '%c'\n",num,num,num);\
	printf("=====: 0x%04x %s %s %s %s:%s %s %s %s\n",value,BIT(128),BIT(64),BIT(32),BIT(16),BIT(8),BIT(4),BIT(2),BIT(1)); \
	printf("-----------------------------\n");\
	usleep(1);\
	value=((newnum) >> 4); \
	extra=(flag ? 0 : 16) | 32 | 128; \
	OUTPUT\
	value=((newnum) >> 4); \
	extra=(flag ? 0 : 16); \
	OUTPUT\
		value=((newnum) & 0x0F);\
		extra=(flag ? 0 : 16) | 32 | 128 ;  \
		OUTPUT\
		value=((newnum) & 0x0F);\
		extra=(flag ? 0 : 16); \
		OUTPUT\
		usleep(1);\
}

int
main()
{
    int fd;
	int i;
    fd = open("/sys/bus/i2c/devices/0-0027/direction", O_WRONLY);
    printf("fd is %d\n", fd);
    write(fd,"0",1);	
    close(fd);

    fd = open("/sys/bus/i2c/devices/0-0027/output", O_WRONLY);
    printf("fd is %d\n", fd);

// initialize the LCD module
    WriteCommByte(0x28, 1);				   // "Function Set" in 4 bits mode
    WriteCommByte(0x0F, 1);				   // "Display ON" with cursors ON
    WriteCommByte(0x01, 1);				   // "Clear Display", can take up to 1.64ms, so the delay
    usleep(200000);
// display "hello"
    WriteCommByte('h', 0);
    WriteCommByte('e', 0);
    WriteCommByte('l', 0);
    WriteCommByte('l', 0);

    WriteCommByte('o', 0);
    WriteCommByte(' ', 0);
    WriteCommByte('w', 0);
    WriteCommByte('o', 0);
    for(i=0;i<40-8;i++) {
       WriteCommByte('r', 0);
    }


    WriteCommByte('r', 0);
    WriteCommByte('l', 0);
    WriteCommByte('d', 0);
    close(fd);
}

