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

// Port A data register
#define LED_PORT PORTA
// Port A data direction register
#define LED_DIR  DDRA
// Port A input pins
#define LED_PINS PINA
// Pin number where LED is connected
#define LED_PIN  (1 << PA3)
// Same for the button
#define BTN_PORT PORTA
#define BTN_DIR  DDRA
#define BTN_PINS PINA
#define BTN_PIN  (1 << PA7)

// Pin change interrupt enable bit for PCINT7..0
#define BTN_INTERRUPT     (1 << PCIE0)
// PCINT corresponding to the button's pin
#define BTN_INTERRUPT_PIN (1 << PCINT7)

static volatile int pressed = 0;
ISR(PCINT0_vect) {
  if(!pressed){
    LED_PORT ^= LED_PIN;
  }
  pressed = ~pressed;
}

int main(void) {
  LED_PORT |= LED_PIN;
  LED_DIR |= LED_PIN;

  BTN_PORT |= BTN_PIN;
  BTN_DIR &= ~BTN_PIN;

  // Set the clock division to 1 to operate at 20MHz
  CLKPR = (1 << CLKPCE);
  CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);

  // Enable interrupts for port A
  GIMSK |= BTN_INTERRUPT;
  // Enable pin change interrupts for pin A7
  PCMSK0 |= BTN_INTERRUPT_PIN;

  // Enable interrupts - sets the interrupt enable bit
  sei();

  LED_PORT &= ~LED_PIN;

  MCUCR |= (1 << SM1) | (1 << SM0);

  //sleep_mode();

  while(1){
    // Wait for interrupt
    sleep_mode();
  }
}