#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "general.H"
#include "cli.H"
#include "x10map.H"


int setunit(int housecode, int unit, char **argv)
{
	struct x10state state;
	int nstate;

	if (!unit)
		return (FAIL_UNITNEEDED);

	int status = mapX10state (housecode, unit, &state,
				  MAPSTATE_READ_TO_WRITE);
	if (status != SUCCESS)
		return (status);

	while (*argv) {
		char *flagstr = *argv;
		nstate = (*flagstr == '-');
		if (nstate)
			flagstr++;
		int flag = get_token (flagstr, x10flags);
		if (!flag) {
			fprintf (stderr, "%s: Unknown flag %s.\n",
				program_name, flagstr);
			return (FAIL_PARSE);
		}
		if ((flag == XS_UPONLY || flag == XS_DOWNONLY) && !nstate) {
			state.flags = state.flags & ~(XS_UPONLY | XS_DOWNONLY);
		}
		state.flags = nstate ? (state.flags & ~flag) 
				     : (state.flags | flag);
		argv++;
	}
	status = mapX10state (housecode, unit, &state, MAPSTATE_WRITE);
	if (status == SUCCESS) {
		showunit (housecode, unit, NULL);
	}
	return (status);
}

