#ifndef _EEPROM_H
#define _EEPROM_H

#include "hardware.h"

#define MEM_COUNT        100
#define N_MEM_MENU       0
#define N_MEM_RADIO_MIN  20
#define N_MEM_RADIO_MAX  420
#define STEPS_MAX        11

uint8_t buff[8]; 
uint32_t FrcvWorkMEM  = 100000;
unsigned char FindStepMEM   = 6;
volatile int8_t  IndMEM     = 1;
unsigned char APU_intMEM    = 20;              //уровень шумодава в шим
unsigned char N_ViewMEM     = FMetr;           //
unsigned char ARU_intMEM    = 255;             //уровень АРУ
unsigned char Sleep_intMEM  = 10;              //время сна в сек

unsigned char Resiver_modeMEM = WFM_STEREO;

////////////
void wEEPROM(uint16_t addr, uint8_t byte)
{
     while(bit_is_set(EECR,EEWE))
     {
       Nop();
     }
     EEAR = addr;
     EEDR = byte;
     cli ();
	 SetBit(EECR,EEMWE);
	 SetBit(EECR,EEWE ); // start write to eeprom
     sei ();
     return;
}

///////////////
uint8_t rEEPROM(uint16_t addr)
{
     while(bit_is_set(EECR,EEWE))
     {
       Nop();
     }
     EEAR = addr;
     SetBit(EECR,EERE);
     return(EEDR);
}

///////////////
void wBufEEPROM(uint16_t addr, uint8_t *buff, uint8_t size)
{
     uint8_t i;

     for(i=0; i < size; i++)
     {
       wEEPROM(addr++,*buff); buff++;
     }
     return;
}

///////////////
void rBufEEPROM(uint16_t addr, uint8_t *buff, uint8_t size)
{
     uint8_t i;

     for(i=0; i < size; i++)
     {
	    *buff = rEEPROM(addr++);
	    buff++;
     }
     return;
}


////////////////
void wMEM_Freq(void)
{
     memcpy(buff,(uint8_t *)&FrcvWorkMEM,4);

     buff[3] = Resiver_modeMEM;

     wBufEEPROM ((uint16_t)IndMEM, buff, 4);
	 
}

//////////////////
uint8_t rMEM_Freq(void)
{
    rBufEEPROM ((uint16_t)IndMEM, buff, 4);

    Resiver_modeMEM = buff[3];
    if(Resiver_modeMEM == WFM_STEREO ||   
	   Resiver_modeMEM == WFM_MONO   ||
	   Resiver_modeMEM == NFM)
	  memcpy((uint8_t *)&FrcvWorkMEM,buff,3);
	else
    {
	   FrcvWorkMEM = 0;
       Resiver_modeMEM = ERROR; 
       return 0; 
	} 
    return 1;
}

////////////////
void wMEM_Options(void)
{
    wEEPROM(1, APU_intMEM);  
	wEEPROM(2, N_ViewMEM); 		
	wEEPROM(4, ARU_intMEM);
	wEEPROM(5, Sleep_intMEM);
	wEEPROM(6, FindStepMEM);
	    
	///////////////
    memcpy(buff,(uint8_t *)&FrcvWorkMEM,4);
    buff[3] = Resiver_modeMEM;
    wBufEEPROM (7, buff, 4);    	 	 
}

//////////////////
uint8_t rMEM_Options(void)
{
    APU_intMEM   = rEEPROM(1);
	N_ViewMEM       = rEEPROM(2);
    ARU_intMEM   = rEEPROM(4);
	Sleep_intMEM = rEEPROM(5);
	FindStepMEM  = rEEPROM(6);
    
    if(Sleep_intMEM < 3)        return 0;
    if(FindStepMEM > STEPS_MAX) return 0;

    rBufEEPROM (7, buff, 4);
	Resiver_modeMEM = buff[3];
	
	if(Resiver_modeMEM == WFM_STEREO ||   
	   Resiver_modeMEM == WFM_MONO   ||
	   Resiver_modeMEM == NFM)
	   memcpy((uint8_t *)&FrcvWorkMEM,buff,3);
	else
    {
	   FrcvWorkMEM = 0;
       Resiver_modeMEM = ERROR; 
       return 0; 
	}
    return 1;
}

#endif