/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
  Part of the Wiring project - http://wiring.org.co

  Copyright (c) 2004-07 Hernando Barragan

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA
*/

#include "WProgram.h"

extern "C" {
//  #include <stdio.h>
//  #include <string.h>
//  #include <inttypes.h>

//  #include "WConstants.h"

  extern void pinMode(uint8_t, uint8_t);
  extern void digitalWrite(uint8_t, uint8_t);
  extern uint8_t digitalRead(uint8_t);
  extern void portMode(uint8_t, uint8_t);
  extern void portWrite(uint8_t, uint8_t);
  extern uint8_t portRead(uint8_t);
}

#include "WEEPROM.h"

/*
uint16_t WEEPROM::read(uint16_t address)
{
  return eeprom_read_word((uint16_t *) address);
}

void WEEPROM::write(uint16_t address, uint16_t value)
{
  eeprom_write_word((uint16_t *) address, value);
}
*/


uint8_t WEEPROM::read(uint16_t address)
{
  while( EECR & _BV(EEWE) );

  EEARH = (uint8_t) ((address & 0xFF00) >> 8);
  EEARL = (uint8_t) (address & 0x00FF);
    
  // set read EERE
  EECR |= _BV(EERE);
    
  // return data byte 
  return EEDR;
}

void WEEPROM::write(uint16_t address, uint8_t value)
{
  // wait until any previous write is done
  while( EECR & _BV(EEWE) );

  EEARH = (uint8_t) ((address & 0xFF00) >> 8);
  EEARL = (uint8_t) (address & 0x00FF);

  EEDR = value;

  // set master write enable EMWEE
  EECR |= _BV(EEMWE);

  // Set write EEWE 
  EECR |= _BV( EEWE );
}


WEEPROM EEPROM;

