#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	int fd = open("/dev/i2c-2", O_RDWR);
	//int i;
	int r;
	//unsigned char dac = strtoul(argv[1], NULL, 10) & 0x03;
	unsigned char dac = strtoul(argv[1], NULL, 10);
	//unsigned short value = strtoul(argv[2], NULL, 10) & 0xffff;
	unsigned short value = strtoul(argv[2], NULL, 10);
	unsigned char buf[3] = { dac };

	// erstes Argument (0) ist Programmname
	if (argc != 3) {
		fprintf(stderr, "\nUngueltige Argumente!\n");
		fprintf(stderr, "Argument 1: DAC-Kanal [0-3]\n");
		fprintf(stderr, "Argument 2: DAC-Wert [0-1023]\n\n");
		return 1;
		exit(0);
	}

	// oeffne Device
	if (fd < 0) {
		fprintf(stderr, "\nDevice kann nicht geoeffnet werden!\n");
		return 2;
	}
	// verbinde zu Slave-Adresse
	if (ioctl(fd, I2C_SLAVE, 0x58) < 0) {
		fprintf(stderr, "\nSlave nicht gefunden!\n");
		close(fd);
		return 3;
	}

	printf("\nEingabe:\n");
	printf("=======\n");
	printf("Kanal = %d\n", dac);
	printf("DAC = %d\n", value);

	if ( (dac < 0 ) | (dac > 3) ) {
		fprintf(stderr, "\nKanal ungueltig! [0-3]\n\n");
		return 4;
		exit(0);
	}

	if ( (value < 0 ) | (value > 1023) ) {
		fprintf(stderr, "\nWert ungueltig! [0-1023]\n\n");
		return 5;
		exit(0);
	}

	// LOW- und HIGH-Byte berechnen
	//buf[1] = value % 256;	// DAC LOW-Byte
	//buf[2] = value / 256;	// DAC HIGH-Byte
	buf[1] = value & 0xff;	// DAC LOW-Byte
	buf[2] = value >> 8;	// DAC HIGH-Byte

	// Buffer ausgeben
	printf("\nZeiger = %d\n", buf[0]);
	printf("LOW-Byte = %d\n", buf[1]);
	printf("HIGH-Byte = %d\n", buf[2]);
	//for ( i=0; i < sizeof(buf); i++ ) {
      	//	printf("%u\n", buf[i]);
   	//}

	// schreibe 3 Byte an Device
	r = write(fd, buf, sizeof(buf));
	if (r < 0) {
		close(fd);
		return 6;
	}

	putchar('\n');
	return 0;
}