#include "EEPROM_Fast.h"
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ISR(EE_READY_vect){

	while (1) {
		if (EEPROM_BUF_COUNT == 0){
			IDIBUS_MODULE.LONG_OP.State = IDILONGOP_STATE_COMPLETE_NO_ERR;				//isThisSafe???!!!
			IDIBUS_MODULE.LONG_OP.Switch = 0;
			IDIBUS_MODULE.LONG_OP.Type = IDIBUS_LONGOP_NOPE;
			EECR &= ~(1<<EERIE);
			return;		
		}
		
		EEAR = EEPROM_ADDR+EEPROM_BUF_COUNT-1;
		EECR |= (1<<EERE);
		uint8_t EEDRold = EEDR;
		
		if (EEDRold == EEPROM_BUF[EEPROM_BUF_COUNT-1])
			EEPROM_BUF_COUNT--;
		else
			break;
	}

	EEDR = EEPROM_BUF[EEPROM_BUF_COUNT-1];
	EEPROM_BUF_COUNT--;
	EECR |=  (1<<EEMPE);
	EECR |=  (1<<EEPE);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void EEPROM_WriteEepBuf(uint8_t count,uint16_t addr){
	if (count > EEPROM_BUF_SIZE || count == 0) {
		IDIBUS_MODULE.LONG_OP.State = IDILONGOP_STATE_COMPLETE_WITH_ERR;				//isThisSafe???!!!
		IDIBUS_MODULE.LONG_OP.Switch = 0;
		IDIBUS_MODULE.LONG_OP.Type = IDIBUS_LONGOP_NOPE;
		return;
	}
	EEPROM_BUF_COUNT = count;
	EEPROM_ADDR = addr;
	IDIBUS_MODULE.LONG_OP.Switch = 1;

	while (1) {
		if (EEPROM_BUF_COUNT == 0){
			IDIBUS_MODULE.LONG_OP.State = IDILONGOP_STATE_COMPLETE_NO_ERR;				//isThisSafe???!!!
			IDIBUS_MODULE.LONG_OP.Switch = 0;
			IDIBUS_MODULE.LONG_OP.Type = IDIBUS_LONGOP_NOPE;
			EECR &= ~(1<<EERIE);
			return;
		}	
		
		EEAR = EEPROM_ADDR+EEPROM_BUF_COUNT-1;

		while(EECR&(1<<EEPE));	//Wait if we somehow doing write
		EECR |= (1<<EERE);
		uint8_t EEDRold = EEDR;
		
		if (EEDRold == EEPROM_BUF[EEPROM_BUF_COUNT-1])
			EEPROM_BUF_COUNT--;
		else
			break;
	}
	cli();
	EEDR = EEPROM_BUF[EEPROM_BUF_COUNT-1];
	EEPROM_BUF_COUNT--;
	EECR |= (1<<EERIE);
	EECR |=  (1<<EEMPE);
	EECR |=  (1<<EEPE);
	sei();
}
