/*
 * wrled -- manipulates the LEDs of PCEngines WRAP
 * Copyright (C) 2006 Jon Langseth
 *
 * This code does not read or manipulate the switch
 * of the board at all, it only manipulates the LEDs.
 *
 * You can choose to set/unset one or more individual leds
 * by using the -1, -2 and -3 options, or you can manipulate
 * all LEDs at once using options -a, -s or -b.
 * -1, -2, -3 and -a takes mandatory boolean parameters
 * turning individual or all LEDs on (1) or off (0).
 * -s and -b takes mandatory integer parameters in the
 * range 1 through 9, and either blinks or "scrolls" the
 * LEDs for the number of seconds the parameter specifies.
 * 
 * Code initially started as a modification of wrap-led 
 * by Michael Hanselmann (C) 2006, but has changed drastically
 * from it's base. Some 10-20 lines are simmilar in this version.
 * Thanks for the help understanding the WRAP LED "interface".
 *
 * Oh, yeah, final note. The code is somewhat wide! The widest line
 * ends its comment at column 112..
 *
 * ------------------   LICENSE  ----------------------------------
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include <errno.h> 	// for errno, perror and family
#include <stdint.h> 	// for standard integer definitions, like uint16_t
#include <sys/io.h> 	// direct IO communication
#include <string.h> 	// string operations like strlen
#include <stdio.h> 	// standard I/O like printf
#include <unistd.h> 	// STDOUT_FILENO defined here..
#include <stdlib.h> 	// Provides exit() sleep()

// GPIO BASE from WRAP datasheet, using tinyBIOS access
#define GPIOBASE 0xF400

/* 
 * The set_ledX() functions actually do the work of setting/unsetting the LEDs.
 * Before any of these can be called, the GPIOBASE needs to be defined, as
 * seen above, and the correct I/O privileges need to be aqquired, as done
 * in main()
 * The functions are so simmilar, that only one of them gets commented...
*/
void set_led1 (int val) {
	// Even though val here is an int, it is used as a boolean..
	// A 1 or true turns on the led, a 0 (false) turns it off.
	
	uint16_t leds;			// Used to store LED values after
					// read and before set..

	leds = inw(GPIOBASE);		// Read in current value of the
					// GPIO region containing the LED bit.

	/*
	 * The LEDs are maipulated with a bit-by-bit manipulations, where two of
	 * the LEDs are available as bit 2 and 3 (2^2, 2^3) at the 16-bit data at 
	 * address 0xF400, and the third as bit 2 at address 0xF402. The pin-value
	 * is inverse of the desired "result", as such, set bit 2 at 0xF400 to zero
	 * to turn LED1 on. This calls for the use of AND / OR operations on the
	 * "current" contents of the GPIO.
	 * Much of the sample code I have seen uses bit-shift-operations and one's
	 * complement to achieve this, but I prefer using the actual numerical values..
	 * The two statements below would in bit-shift-operation notion be :
	 *    leds &= ~(1 << 2);
	 *    leds |=  (1 << 2);
	 */

	if ( val ) {			// Want to turn it on?
		leds &= 65531;		// Set the LED's bit to zero
	} else {			// Want to turn it off?
		leds |= 4;		// Set the LED's bit to one
	} 
	outw(leds, GPIOBASE);		// Write the new register value out.
	
}

void set_led2 (int val) {
	uint16_t leds;

	leds = inw(GPIOBASE);

	if ( val ) {
		leds &= 65527;
	} else {
		leds |= 8;
	} 
	outw(leds, GPIOBASE);
}

void set_led3 (int val) {
	uint16_t leds;

	leds = inw(GPIOBASE + 0x2);

	if ( val ) {
		leds &= 65531;
	} else {
		leds |= 4;
	} 
	outw(leds, GPIOBASE + 0x2);
}

void set_leds (int val) {
	uint16_t leds;

	leds = inw(GPIOBASE);

	if ( val ) {
		leds &= 65531;
		leds &= 65527;
	} else {
		leds |= 4;
		leds |= 8;
	} 
	outw(leds, GPIOBASE);

	leds = inw(GPIOBASE + 0x2);

	if ( val ) {
		leds &= 65531;
	} else {
		leds |= 4;
	} 
	outw(leds, GPIOBASE + 0x2);
}

void phelp (void) {
	fprintf(stderr, "Error detected.\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "Usage summary is as follows:\n");
	fprintf(stderr, "command (['-1' b] ['-2' b] ['-3' b]) | '-b' t | '-s' t | '-a' b\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "-1 sets led 1 to boolean value b\n");
	fprintf(stderr, "-2 sets led 2 to boolean value b\n");
	fprintf(stderr, "-3 sets led 3 to boolean value b\n");
	fprintf(stderr, "-b blinks all leds for t seconds (1-9 secs range)\n");
	fprintf(stderr, "-s scrolls all leds right for t seconds (1-9 secs range)\n");
	fprintf(stderr, "-S scrolls all leds left for t seconds (1-9 secs range)\n");
	fprintf(stderr, "-a sets all leds to boolean value b\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "Specify EITHER ONE of the options -a, -b, -s\n");
	fprintf(stderr, "OR one or more of the options 1, 2, 3 \n");

}

int main(int argc, char* argv[]) {

	int c;		// Used to store option character for getopt()
	int tmp;  	// Temporary storage variable. Used in getopt shiwtch/case block
	int single_led;	// Flag to indicate that single-led-operations are requested
	int multi_leds;	// Flag indicates that multi-led-operations are requested
	int i;		// Iterator
	int err;	// Set if a command line option error is detected. Causes help to print.
	// The flag variables are set if one of the corresponding options are set on command line
	int flag1, flag2, flag3, flag4, flaga, flagb, flags;
	// The val variables contain the value for the chosen options.
	int val1, val2, val3, val4, vala, valb, vals;

	// Initialize integer flags, values and checks to zero..
	flag1 = flag2 = flag3 = flag4 = flaga = flagb = flags = 
		val1 = val2 = val3 = val4 = vala = valb = vals = 
		single_led = multi_leds = err = 0;

	/*
	 *  iopl(int pl) sets I/O Privilege level to "pl", or returns an error.
	 * I have no idea what the levels mean, but they are probably documented
	 * somewhere... What I DO know after a bit of research, is that an IOPL value
	 * of 3 gives access to all i/o ports in the system, which seems to be
	 * required to access ports above portnumber 0x3FF. An IOPL greater than
	 * 3 causes the iopl() call for throw an error, and an iopl() call with
	 * a value grater than 1 reuquires root access.
	 */

	if(iopl(3)) {	// If iopl() returns anything other than zero, an error occured.
		char *error = strerror(errno);	// Get Posix error string.
		fprintf(stderr, "Opening port failed: ");
		write(STDERR_FILENO, error, strlen(error));
		fprintf(stderr, "\n");
		exit(1); // Die, cause this will not compute...
	}

	/*
	 * Here comes the dreaded getopt() block... I will have to comment this one
	 * some day... While waiting for that, have a look at:
	 * http://www.gnu.org/software/libc/manual/html_node/Getopt.html
	 * Basically, the routine is: set option errors (opterr) to zero, 
	 * then read all options by calling getopt(), which will return an
	 * option character, '?', ':' or -1, and at the same time set optarg
	 * containing the oprtion argument, if any. Do stuff with the options using
	 * a switch/case block.
	 */ 
	opterr = 0;
	while ((c = getopt (argc, argv, "1:2:3:a:S:s:b:")) != -1)
		switch (c)
		{
			case '1':
				single_led++;			// This is a single-led operation
				flag1 = 1;			// Set the corresponging flag
				if ( strlen(optarg) == 1)	// Check that the argument is a single character
					tmp = atoi(optarg);	// Translate the char to an integer
				else
					tmp = -1;		// or set an error code

				if ( (tmp == 0) || (tmp == 1) ) {
								// The argument value is OK
					val1 = tmp;		// so we set the corresponding value variable.
				} else {
								// The argument is not OK...
					fprintf(stderr, "Invalid value\n");
					err++;			// So we indicate this by setting an err...
				}
				break;				// End of this case..
			case '2':				// The rest of theese proceed very simmilarily
				single_led++;
				flag2 = 1;
				if ( strlen(optarg) == 1)
					tmp = atoi(optarg);
				else
					tmp = -1;

				if ( (tmp == 0) || (tmp == 1) ) {
					// OK
					val2 = tmp;
				} else {
					// ERR
					fprintf(stderr, "Invalid value\n");
					err++;
				}
				break;
			case '3':
				single_led++;
				flag3 = 1;
				if ( strlen(optarg) == 1)
					tmp = atoi(optarg);
				else
					tmp = -1;

				if ( (tmp == 0) || (tmp == 1) ) {
					// OK
					val3 = tmp;
				} else {
					// ERR
					fprintf(stderr, "Invalid value\n");
					err++;
				}
				break;
			case 'a':
				multi_leds++;
				flaga = 1;
				if ( strlen(optarg) == 1)
					tmp = atoi(optarg);
				else
					tmp = -1;

				if ( (tmp == 0) || (tmp == 1) ) {
					// OK
					vala = tmp;
				} else {
					// ERR
					fprintf(stderr, "Invalid value\n");
					err++;
				}
				break;
			case 's':
				multi_leds++;
				flags = 1;
				if ( strlen(optarg) == 1)
					tmp = atoi(optarg);
				else
					tmp = -1;

				if ( (tmp > 0) && (tmp < 10) ) {
					// OK
					vals = tmp;
				} else {
					// ERR
					fprintf(stderr, "Invalid value\n");
					err++;
				}
				break;
			case 'S':
				multi_leds++;
				flags = 2;
				if ( strlen(optarg) == 1)
					tmp = atoi(optarg);
				else
					tmp = -1;

				if ( (tmp > 0) && (tmp < 10) ) {
					// OK
					vals = tmp;
				} else {
					// ERR
					fprintf(stderr, "Invalid value\n");
					err++;
				}
				break;
			case 'b':
				multi_leds = 1;
				flagb = 1;
				if ( strlen(optarg) == 1)
					tmp = atoi(optarg);
				else
					tmp = -1;

				if ( (tmp >= 1) && (tmp <= 9) ) {
					// OK
					valb = tmp;
				} else {
					// ERR
					fprintf(stderr, "Invalid value\n");
					err++;
				}
				break;
			case '?':				// getopt encountered an invalid option char..
				if (isprint (optopt))
					fprintf (stderr, "Error in option `-%c'.\n", optopt);
				else
					fprintf (stderr,
							"Unknown option character `\\x%x'.\n",
							optopt);
				err++;
				return 1;
			default:
				err++;
				abort ();
		}

	/*
	 * The rest of the code is nasty application-specific code.
	 * Please feel free to add missing comments to the code, and send it to me...
	 */ 
	if ( (single_led > 0) && (multi_leds > 0)) { 
		// If both single and multiple led options are chosen, this is an error
		err++;
	} else {
		if ( (single_led > 0) && (multi_leds == 0) ) {
			// If only single-led values are chosen (arbitrary number)
			if ( flag1 ) {		// flag1 indicates that led1 should "change" to val1
				set_led1(val1);
			}
			if ( flag2 ) {		// Ditto for flag2
				set_led2(val2);
			}
			if ( flag3 ) {		// you get the point..
				set_led3(val3);
			}
		} else if ( multi_leds == 1 ) {
			// One, and only one, multi-led options are chosen...
			if ( flagb ) {		// flagb indicates that we should blink all leds..
				for (i = 0; i < valb; i++) {
					// By sleeping 1/4 second for each on/off, and turning the
					// leds on two times, off two times, each iteration takes
					// approximately one second.
					set_leds(1);
					usleep(1000000 / 4);
					set_leds(0);
					usleep(1000000 / 4);
					set_leds(1);
					usleep(1000000 / 4);
					set_leds(0);
					usleep(1000000 / 4);
				}
			} else if (flags == 1) {
				// "scroll" the leds in one of two directions. A flags = 1 scrolls left,
				// while a flags = 2 scrolls right...
				for (i = 0; i < vals; i++) {
					// We are doing a little "manual" speedup of the rotation, by doing
					// two rotations per iteration. Between each "flip-to-next-led"
					// a sleep of 1/6 sec makes the iteration take just above 1 sec.
					set_led1(1);
					usleep(1000000 / 6);
					set_led1(0);
					set_led2(1);
					usleep(1000000 / 6);
					set_led2(0);
					set_led3(1);
					usleep(1000000 / 6);
					set_led3(0);
					set_led1(1);
					usleep(1000000 / 6);
					set_led1(0);
					set_led2(1);
					usleep(1000000 / 6);
					set_led2(0);
					set_led3(1);
					usleep(1000000 / 6);
					set_led3(0);
				}
			} else if (flags == 2) {
				// And this is the other rotation. See above for comments.
				for (i = 0; i < vals; i++) {
					set_led3(1);
					usleep(1000000 / 6);
					set_led3(0);
					set_led2(1);
					usleep(1000000 / 6);
					set_led2(0);
					set_led1(1);
					usleep(1000000 / 6);
					set_led1(0);
					set_led3(1);
					usleep(1000000 / 6);
					set_led3(0);
					set_led2(1);
					usleep(1000000 / 6);
					set_led2(0);
					set_led1(1);
					usleep(1000000 / 6);
					set_led1(0);
				}
			} else if (flaga) {
				// flaga tells us that all leds should be "changed" to vala
				set_leds(vala);

			} else {
				// Ok, multi_leds was set, but none of the appropriate flags were.
				// This is clearly an err....
				err++;
			}
		} else {
			// This else tells us that either both single and multi options were selected,
			// or that more than one multi vas selected.. Clearly an err...
			err++;
		}
	}

	if ( err > 0 ) {
		// If we have encountered an err earlier in the code, no operations have been performed.
		// It is now time to tell the user that he/she made a boooobooo
		phelp();
		// The number of booobooo's accumulated is given as a return code..
		exit(err);
	}

	// Well, quite simply done...
	return 0;
}

