#include "EEPROM.h"

namespace EEPROM {
    void set(uint16_t address, uint8_t data) {
        if (get(address) != data) {
            /* Wait for completion of previous write */
            while (EECR & (1 << EEPE));
            /* Set up address and Data Registers */
            EEAR = address;
            EEDR = data;
            /* Write logical one to EEMPE */
            EECR |= (1 << EEMPE);
            /* Start eeprom write by setting EEPE */
            EECR |= (1 << EEPE);
        }
    }

    void set(uint16_t address, void *dataSource, size_t dataSize) {
        uint8_t *data = (uint8_t *) dataSource;
        for (size_t i = 0; i < dataSize; i++) {
            set(address + i, data[i]);
        }
    }

    uint8_t get(uint16_t address) {
        /* Wait for completion of previous write */
        while (EECR & (1 << EEPE));
        /* Set up address register */
        EEAR = address;
        /* Start eeprom read by writing EERE */
        EECR |= (1 << EERE);
        /* Return data from Data Register */
        return EEDR;
    }

    void get(uint16_t address, void *dataDest, size_t dataSize) {
        uint8_t *data = (uint8_t *) dataDest;
        for (size_t i = 0; i < dataSize; i++) {
            data[i] = get(address + i);
        }
    }

}
