#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "x10map.H"
#include "general.H"
#include "cli.H"

void printflags(int flags)
{
	printf(" %s", (flags & XS_EXIST) ? "EXIST" : "     ");
	printf(" %s", (flags & XS_TWOWAY) ? "TWOWAY" : "      ");
	printf(" %s", (flags & XS_ALIVE) ? "ALIVE" : "     ");
	printf(" %s", (flags & XS_LIGHT) ? "LIGHT" : "     ");
	printf(" %s", (flags & XS_ON) ? "ON" : "  ");
	printf(" %s", (flags & XS_ME) ? "ME" : "  ");
	switch (flags & (XS_UPONLY | XS_DOWNONLY)) {
		case (0):           printf ("          "); break;
		case (XS_UPONLY):   printf ("UPONLY    "); break;
		case (XS_DOWNONLY): printf ("DOWNONLY  "); break;
		default:            printf ("BOGUS     ");
	}
}


int showunit(int housecode, int unit, char **argv)
{
	struct x10state state;
	int status;

	if (unit == 0) {
		printf("UNIT\tFLAGS\t\t\t\t\t\tLEVEL\n");
		for (unit = 1; unit <= 16; unit++) {
			status = mapX10state (housecode, unit, &state);
			if (status != SUCCESS)
				return (status);
			printf("%c%02d\t", (char) housecode, unit);
			printflags(state.flags);
			printf("\t%d", state.level);
			printf("\n");
		}
		return (status);
	}

	status = mapX10state (housecode, unit, &state);
	if (status != SUCCESS)
		return (status);
	printf("Flags:");
	printflags (state.flags);
	printf("\nDimmer level: %d\n", state.level);
	if (state.flags & XS_ME) {
		printf (state.ifunc ? "Command handled internally (%p)\n"
			: "Command handled by external program\n",
			state.ifunc);
	}
	return (status);
}

