#include <avr/io.h>
#include <util/delay.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/wdt.h>

#include "lights.h"

static void hw_setup()
{
	power_all_disable();

	wdt_enable(WDTO_1S);

	init_battery();
	init_pwm();
	init_adc();

	init_buttons();

	init_pwmled();
	init_pattern();
	init_control();

	set_sleep_mode(SLEEP_MODE_IDLE);
}

static void hw_suspend()
{
	susp_pwm();
	susp_adc();
	susp_buttons();

	wdt_disable();
	power_all_disable();
}

void power_down()
{
	hw_suspend();

	do {
		// G'night
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_enable();
		sleep_bod_disable();
		sei();
		sleep_cpu();

		// G'morning
		cli();
		sleep_disable();

		// allow wakeup by long button-press only
	} while (!buttons_wait_for_release());

	// ok, so I will wake up
	hw_setup();
}

int main(void)
{
	init_log();

	log_set_state(3);

	hw_setup();
	power_down();

	sei();
#if 1
	while (1) {
		wdt_reset();
		sleep_mode();
	}
#endif

#if 0
	DDRB |= _BV(PB2);
	while (1) {
		PORTB |=  _BV( PB2 );
		_delay_ms(200);
		PORTB &=~ _BV( PB2 );
		_delay_ms(200);
	}
#endif
}
