Window(C="Megamos48";left = 5;top=5;w=800;h=290)
{
     group(c="Crypt Key";left = 490;top=300;width = 268;h=280)
     {
	
	//	CRYPT KEY
	
	Label (C = "Word"; name = lbWord0; left = 34; top = 40)
	Label (C = "Crypt Key"; name = lbCryptKey; left = 74; top = 40)
		//Label (C = "9"; name = lbWord9; left = 53; top = 50)
	HexBytes(C = "9   "; left = 75; top = 70; w = 49; value = 2; name = hbWord9; items="00 00")
	Label (C = " ..... "; name = lbDots9; left = 127; top = 70)
	Button(C = "Запись"; proc = writeWord9; left = 150; top = 70; width = 50; h = 21)
		
		//Label (C="Word8:";name = lbWord8;left = 53;top = 73)
	HexBytes(C = "8   "; left = 75; top = 110; w = 49; value = 2; name = hbWord8; items = "")
	Label (C = " ..... "; name = lbDots8; left = 127; top = 110)
	Button(C = "Запись"; proc = writeWord8; left = 150; top = 110; width = 50; h = 21)
		
		//Label (C="Word7:";name = lbWord7;left = 53;top = 103)
	HexBytes(C = "7   "; left = 75; top = 150; w = 49; value = 2; name = hbWord7; items = "")
	Label (C = " ..... "; name = lbDots7; left = 127; top = 150)
	Button(C = "Запись"; proc = writeWord7; left = 150; top = 150; width = 50; h = 21)
		
		//Label (C="Word6:";name = lbWord6;left = 53;top = 133)
	HexBytes(C = "6   "; left = 75; top = 190; w = 49; value = 2; name = hbWord6; items = "")
	Label (C = " ..... "; name = lbDots6; left = 127; top = 190)
	Button(C = "Запись"; proc = writeWord6; left = 150; top = 190; width = 50; h = 21)
		
		//Label (C="Word5:";name = lbWord5;left = 53;top = 163)
	HexBytes(C = "5   "; left = 75; top = 230; w = 49; value = 2; name = hbWord5; items = "")
	Label (C = " ..... "; name = lbDots5; left = 127; top = 230)
	Button(C = "Запись"; proc = writeWord5; left = 150; top = 230; width = 50; h = 21)
		
		//Label (C="Word4:";name = lbWord4;left = 53;top = 193)
	HexBytes(C = "4   "; left = 75; top = 270; w = 49; value = 2; name = hbWord4; items = "")
	Label (C = " ..... "; name = lbDots4; left = 127; top = 270)
	Button(C = "Запись"; proc = writeWord4; left = 150; top = 270; width = 50; h = 21)
    }
	
  button(c="Check key";left=475; top=225;width=100;h=25;proc = view_key)

     group(c="ID LB1/LB0/UM";left = 2750;top=5;width = 368;h=330)
     {

	// ID
	
	Label (C = "Word"; name = lbWord1; left = 40; top = 40)
	Label (C = "ID"; name = lbID; left = 80; top = 40)
	HexBytes(C = "3..2   "; left = 80; top = 70; w = 97; value = 4; name = hbBlock32; items = "00 00 00 00")
	Button(C = "Чтение"; proc = ReadID; left = 183; top = 70; width = 50; h = 21)
    //}
	
	//	LB1/LB0/UM
	
	Label(C = "Word"; name = lbWord2; left = 40; top = 120)
	Label(C = "UM"; name = lbWord10; left = 80; top = 120)
	HexBytes(C = "1..0   "; left = 80; top = 150; w = 97; value = 4; name = hbBlock10; items = "00 00 00 00")
	Button(C = "Чтение"; proc = readBlock10; left = 183; top = 150; width = 50; h = 21)
	Label(C = " ..... "; name = lbDots10; left = 236; top = 150)
	Button(C = "Запись"; proc = writeBlock10; left = 260; top = 150; width = 50; h = 21)
	
	Label(C = "Bits"; name = lbBits; left = 87; top = 185)
	Label(C = "Lock Bits"; name = lbLCKBits; left = 117; top = 185)
	
	Label(C = "  31"; name = lbBit31; left = 85; top = 203)
	Label(C = "  30"; name = lbBit30; left = 85; top = 223)
	CheckBox(c = "LB1"; l = 115; top = 205; name = cbLB1; value = 0)
	CheckBox(c = "LB0"; l = 115; top = 225; name = cbLB0; value = 0)
	Label(C = " ................... "; name = lbDotsLBs; left = 177; top = 215)
	Button(C = "Запись"; proc = writeLockBits; left = 243; top = 215; width = 50; h = 21)
	
	//Label(C = "29..0"; name = lbBit290; left = 130; top = 305)
	Label(C = "User Mem."; name = lbUserMem; left = 117; top = 250)
	HexBytes(C = "29..0   "; left = 117; top = 270; w = 97; value = 4; name = hbUserMem; items = "00 00 00 00")
	Label (C = " ..... "; name = lbDotsUserMem; left = 218; top = 270)
	Button(C = "Запись"; proc = writeUserMem; left = 242; top = 270; width = 50; h = 21)
  }
group(c="Key ID";left = 45;top=5;width = 280;h=200)
 
     {

    Label(c = "Dump:"; name = lbState; left = 155; top = 35; width = 100; height = 20)
    Label(c = "Не проверен!"; name = lbDumpState; left = 200; top = 35; width = 100; height = 20)
    
    
    button(c="View ID key";left=5; top=30;width=140;h=25;proc = show_key1)
    HexBytes(C="ID -1 ";left = 35;top = 70;w = 95;value = 4;name = Page11;items="FF FF FF FF") 
    HexBytes(C="ID -2 ";left = 35;top = 100;w = 95;value = 4;name = Page12;items="FF FF FF FF")    
    HexBytes(C="ID -3 ";left = 35;top = 130;w = 95;value = 4;name = Page13;items="FF FF FF FF") 
    HexBytes(C="ID -4 ";left = 35;top = 160;w = 95;value = 4;name = Page14;items="FF FF FF FF") 
    
   
   }
  
     group(c="Write Key";left = 335;top=5;width = 270;h=200)
 
     {
            Label(c = "Click Write key1!"; name = keychek1; left = 135; top = 30; width = 100; height = 20)
            button(c="Write key 1";left=25; top=25;width=100;h=25;proc = new_key1)

            Label(c = "Click Write key2!"; name = keychek2; left = 135; top = 70; width = 100; height = 20)
            button(c="Write key 2";left=25; top=65;width=100;h=25;proc = new_key2)

            Label(c = "Click Write key3!"; name = keychek3; left = 135; top = 110; width = 100; height = 20)
            button(c="Write key 3";left=25; top=105;width=100;h=25;proc = new_key3)

            Label(c = "Click Write key4!"; name = keychek4; left = 135; top = 150; width = 100; height = 20)
            button(c="Write key 4";left=25; top=145;width=100;h=25;proc = new_key4)
     }

    group(c="Status Dump";l = 45; t = 210; w = 385; h = 50)
    {
    Label(c = " "; name = eeprom_chek; left = 135; top = 20; width = 500; height = 20)

    }


    group(c="Внешний вид";l = 615; t = 5; w = 185; h = 160)
    {
    picture(c="Fiat.jpg"; l = 15; t = 18; w = 0; h = 0)
    }

}  

Editor
{
 (C="EEPROM";size=256;mode=16;bytes=16)
}
   
$HOST

emem eeprom=0,mismatch=2;

#define MEM_SIZE        128         // размер памяти микросхемы в байтах
#define BLOCK_SIZE      64          // размер блока для обмена между компьютером и программатором
                                    // блоковая передача применяется для ускорения обмена
                                    // передача одиночных байт туда-сюда через USB сильно замедляет обмен
                                    // для микросхем с объемом более 1024 байт торможение будет недопустимым    
#define WRITE_PAGE_SIZE 8

emem fbuf=0,fsel=2;                 // объявляем буфера
                                    // fbuf - то, что видно на экране программы
                                    // fsel - для включения-выключения подсветки байт или слов                
byte ss1;
 byte s;
byte buf[BLOCK_SIZE];
 byte  bits[8] ;
byte buffer[64];


proc debug_out()
{
	var a, i, n;
	
	a = device.dbg_timer;
	print("\nDBG_TIMER: " + #i.a);
	n = device.dbg_n;
	print("\nDBG_N: " + #i.n);
	print("\n");
	i = 0;
	while(i != n)
	{
		a = device.dbgu[i];
		
		print("" + #i.a + " ");
		if((i & 0xF) = 0xF){ print("\n"); }
		i = i + 1;
	}
	
	print("\n");
}

proc AUTH() 
{
	var a;
	
	print("\n Check adapter... ");
	
	device.pwr(3);
	delay(50);
	a = device.InitHTRC();
	delay(50);
	if(a = 1)
	{
		print("not ready.");
		device.pwr(0);
		return(0);
	}
	
	print("OK.");
	
	a = device.Ast_Adjust(0x3F);
	
	//for(a = 0; a < 144; a++) eeprom[a] = 0xFF;   // содержимое редактора = 0xFF
	
	a = device.Restart_Transponder();
	
	return(1);
	
}

///////////////// Crypt Key //////////////////

proc writeWord9()
{
	var a;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write Word 9(Crypt Key)..");
	
	hbWord9.color = 0xFFFFFF;
	
	//print("\n	write data..");
	a = device.WriteWord(9, hbWord9[0], hbWord9[1]);
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbWord9.color = 0x0000FF;
	}
	
	device.pwr(0);
}

proc writeWord8()
{
	var a;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write Word 8(Crypt Key)..");
	
	hbWord8.color = 0xFFFFFF;
	
	//print("\n	write data..");
	a = device.WriteWord(8, hbWord8[0], hbWord8[1]);
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbWord8.color = 0x0000FF;
	}
	
	device.pwr(0);
}

proc writeWord7()
{
	var a;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write Word 7(Crypt Key)..");
	
	hbWord7.color = 0xFFFFFF;
	
	//print("\n	write data..");
	a = device.WriteWord(7, hbWord7[0], hbWord7[1]);
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbWord7.color = 0x0000FF;
	}
	
	device.pwr(0);
}

proc writeWord6()
{
	var a;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write Word 6(Crypt Key)..");
	
	hbWord6.color = 0xFFFFFF;
	
	//print("\n	write data..");
	a = device.WriteWord(6, hbWord6[0], hbWord6[1]);
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbWord6.color = 0x0000FF;
	}
	
	device.pwr(0);
}

proc writeWord5()
{
	var a;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write Word 5(Crypt Key)..");
	
	hbWord5.color = 0xFFFFFF;
	
	//print("\n	write data..");
	a = device.WriteWord(5, hbWord5[0], hbWord5[1]);
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbWord5.color = 0x0000FF;
	}
	
	device.pwr(0);
}

proc writeWord4()
{
	var a;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write Word 4(Crypt Key)..");
	
	hbWord4.color = 0xFFFFFF;
	
	//print("\n	write data..");
	a = device.WriteWord(4, hbWord4[0], hbWord4[1]);
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbWord4.color = 0x0000FF;
	}
	
	device.pwr(0);
}

///////////////// ID //////////////////

proc ReadID()
{
	var a, t;
	
	a = AUTH(); if(a = 0){ return; }
	device.InitFastTimer();
	
	print("\n    read ID..");
	hbBlock32.color = 0xFFFFFF;
	hbBlock32[0] = 0xFF;
	hbBlock32[1] = 0xFF;
	hbBlock32[2] = 0xFF;
	hbBlock32[3] = 0xFF;
		
	a = device.ReadBlock(1);
	if(a = 0)
	{
		print("Error!");
		hbBlock32.color = 0x0000FF;
	}
	else
	{
		t = device.tag_data; print(#h4.t);
		hbBlock32[0] = ((t >> 24) & 0xFF); 
		hbBlock32[1] = ((t >> 16) & 0xFF);
		hbBlock32[2] = ((t >> 8) & 0xFF);
		hbBlock32[3] = (t & 0xFF);
	}
	
	device.pwr(0);
}

///////////////// UM //////////////////
proc RefreshCtrl_Block10(UMBlock)
{
	hbBlock10[0] = ((UMBlock >> 24) & 0xFF);
	hbBlock10[1] = ((UMBlock >> 16) & 0xFF);
	hbBlock10[2] = ((UMBlock >> 8)  & 0xFF);
	hbBlock10[3] = (UMBlock & 0xFF);
}

proc RefreshCtrl_LCKBits(UMBlock)
{
	if(UMBlock & 0x80000000)
	{
		cbLB1 = 1;
	}
	else
	{
		cbLB1 = 0;
	}
	
	if(UMBlock & 0x40000000)
	{
		cbLB0 = 1;
	}
	else
	{
		cbLB0 = 0;
	}
}

proc RefreshCtrl_UserMem(UMBlock)
{
	hbUserMem[0] = ((UMBlock >> 24) & 0x3F);
	hbUserMem[1] = ((UMBlock >> 16) & 0xFF);
	hbUserMem[2] = ((UMBlock >> 8)  & 0xFF);
	hbUserMem[3] = (UMBlock & 0xFF);
}

proc ResetCtrl_Block10()
{
	hbBlock10[0] = 0xFF;
	hbBlock10[1] = 0xFF;
	hbBlock10[2] = 0xFF;
	hbBlock10[3] = 0xFF;
}

proc ResetCtrl_LCKBits()
{
	cbLB1 = 1;
	cbLB0 = 1;
}

proc ResetCtrl_UserMem()
{
	hbUserMem[0] = 0xFF;
	hbUserMem[1] = 0xFF;
	hbUserMem[2] = 0xFF;
	hbUserMem[3] = 0xFF;
}

proc readBlock10()
{
	var a, t;
	
	a = AUTH(); if(a = 0){ return; }
	device.InitFastTimer();
	
	print("\n    read UM.. ");
	
	hbBlock10.color = 0xFFFFFF;
	hbUserMem.color = 0xFFFFFF;
	ResetCtrl_Block10();
	ResetCtrl_LCKBits();
	ResetCtrl_UserMem();
	
	a = device.ReadBlock(0);
	if(a = 0)
	{
		print("Error!");
		hbBlock10.color = 0x0000FF;
	}
	else
	{
		t = device.tag_data; print(#h4.t);
		RefreshCtrl_Block10(t);
		RefreshCtrl_LCKBits(t);
		RefreshCtrl_UserMem(t);
	}

	device.pwr(0);
}

proc writeBlock10()
{
	var a, t, error;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write LB1/LB0/UM...");
	
	error = 0;
	
	hbBlock10.color = 0xFFFFFF;
	hbUserMem.color = 0xFFFFFF;
	ResetCtrl_LCKBits();
	ResetCtrl_UserMem();
	
	print("\n	write word 0.. ");
	a = device.WriteWord(0, hbBlock10[2], hbBlock10[3]);
	//a = 0;
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbBlock10.color = 0x0000FF;
		error = 1;
	}
	
	print("\n	write word 1.. ");
	a = device.WriteWord(1, hbBlock10[0], hbBlock10[1]);
	//a = 0;
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbBlock10.color = 0x0000FF;
		error = 1;
	}
	//device.pwr(0);
	//return;
	
	if(error = 0)		// не было ошибок? обновляем все поля
	{
		print("\n	update.. ");
		ResetCtrl_Block10();
		ResetCtrl_LCKBits();
		ResetCtrl_UserMem();
		a = device.ReadBlock(0);
		//a = 0;
		if(a = 1)
		{
			print("OK.");
			t = device.tag_data;// print(#h4.t);
			RefreshCtrl_Block10(t);
			RefreshCtrl_LCKBits(t);
			RefreshCtrl_UserMem(t);
		}
		else
		{
			print("Error!");
			hbBlock10.color = 0x0000FF;
			hbUserMem.color = 0x0000FF;
		}
	}
	//debug_out();
	device.pwr(0);
}

proc writeLockBits()
{
	var a, t, th, tl, error;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write Lock Bits...");
	
	error = 0;
	
	print("\n	read UM..");
	hbBlock10.color = 0xFFFFFF;
	hbUserMem.color = 0xFFFFFF;
	ResetCtrl_Block10();
	ResetCtrl_UserMem();
	
	a = device.ReadBlock(0);
	//a = 0;
	if(a = 1)
	{
		//print("OK.");
		t = device.tag_data; print(#h4.t);
		t = (t >> 16) & 0x3FFF;
		//t = t | 0x8000;
		
		if(cbLB1 = 1){ t = t | 0x8000; }
		if(cbLB0 = 1){ t = t | 0x4000; }
		th = (t >> 8) & 0xFF;
		tl = t & 0xFF;
		print("\n	write word 0..");
		a = device.WriteWord(1, th , tl);
		if(a = 1)
		{
			print("OK.");
			print("\n	read UM..");
	
			a = device.ReadBlock(0);
			if(a = 1)
			{
				t = device.tag_data; print(#h4.t);
				hbBlock10.color = 0xFFFFFF;
				hbUserMem.color = 0xFFFFFF;
				RefreshCtrl_Block10(t);
				RefreshCtrl_LCKBits(t);
				RefreshCtrl_UserMem(t);
			}
			else
			{
				print("Error!");
			}
		}
		else
		{
			print("Error!");
		}
	}
	else
	{
		print("Error!");
		hbBlock10.color = 0x0000FF;
		hbUserMem.color = 0x0000FF;
	}
	
	device.pwr(0);
	
	//debug_out();
}

proc writeUserMem()
{
	var a, t, error;
	
	a = AUTH(); if(a = 0){ return; }
	
	device.InitFastTimer();
	print("\n write User Mem...");
	
	error = 0;
	
	hbBlock10.color = 0xFFFFFF;
	hbUserMem.color = 0xFFFFFF;
	ResetCtrl_Block10();
	ResetCtrl_LCKBits();
	
	print("\n	write word 0.. ");
	a = device.WriteWord(0, hbUserMem[2], hbUserMem[3]);
	//a = 0;
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbUserMem.color = 0x0000FF;
		error = 1;
	}
	
	
	print("\n	write word 1.. ");
	t = (hbUserMem[0] & 0x3F) | 0x80;
	a = device.WriteWord(1, t, hbUserMem[1]);
	//a = 0;
	if(a = 1)
	{
		print("OK.");
	}
	else
	{
		print("Error!");
		hbUserMem.color = 0x0000FF;
		error = 1;
	}
	//device.pwr(0);
	//return;
	
	if(error = 0)		// не было ошибок? обновляем все поля
	{
		print("\n	update.. ");
		ResetCtrl_Block10();
		ResetCtrl_LCKBits();
		ResetCtrl_UserMem();
		a = device.ReadBlock(0);
		//a = 0;
		if(a = 1)
		{
			print("OK.");
			t = device.tag_data;// print(#h4.t);
			RefreshCtrl_Block10(t);
			RefreshCtrl_LCKBits(t);
			RefreshCtrl_UserMem(t);
		}
		else
		{
			print("Error!");
			hbBlock10.color = 0x0000FF;
			hbUserMem.color = 0x0000FF;
		}
	}
	//debug_out();
	device.pwr(0);
	//debug_out();
}






//==================Fiat============================









proc RevBIT(adres)
{
 var i,r;
//-----------------
    bits[9]= 0x0;

   bits[1]= (fbuf[adres]<<7);
   i= bits[1]>>7;
   bits[1]=i;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1<<7 )); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 <<7)); }
    

   bits[2]= (fbuf[adres]<<6);
   i=bits[2]>>7;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1 << 6)); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 << 6)); }
    

   bits[3]= (fbuf[adres]<<5);
   i=bits[3]>>7;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1 << 5)); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 << 5)); }
   

   bits[4]= (fbuf[adres]<<4);
   i=bits[4]>>7;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1 << 4)); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 << 4)); }
   

   bits[5]= (fbuf[adres]<<3);
   i=bits[5]>>7;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1 << 3)); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 << 3)); }
    

   bits[6]= (fbuf[adres]<<2);
   i=bits[6]>>7;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1 << 2)); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 << 2)); }
   
  
   bits[7]= (fbuf[adres]<<1);
   i=bits[7]>>7;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1 << 1)); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 << 1)); }
   

   bits[8]= (fbuf[adres]);
   i=bits[8]>>7;
   if(i = 0x1){ bits[9]= (bits[9] + (0x1)); }
   if(i = 0x0){ bits[9]= (bits[9] + (0x0 )); }
   

    i=bits[9]; 
    ss1=i;

}





//------cript1-----

proc cript1()
{
   
   var  i,z,b,c,d,vozvr;
 
  



c=RevBIT(0x21);
hbWord9[0]=ss1;
c=RevBIT(0x22);
hbWord9[1]=ss1;      

c=RevBIT(0x23);
hbWord8[0]=ss1;
c=RevBIT(0x24);
hbWord8[1]=ss1; 

c=RevBIT(0x25);
hbWord7[0]=ss1;
c=RevBIT(0x26);
hbWord7[1]=ss1; 

c=RevBIT(0x27);
hbWord6[0]=ss1;
c=RevBIT(0x28);
hbWord6[1]=ss1;
    
c=RevBIT(0x29);
hbWord5[0]=ss1;
c=RevBIT(0x2A);
hbWord5[1]=ss1;

c=RevBIT(0x2B);
hbWord4[0]=ss1;
c=RevBIT(0x2C);
hbWord4[1]=ss1;


}




proc nkey()
{
var n1,n2,n3,g;

       n1=0;
       if(fbuf[0x04] = 0x00){ n1 = 1; }
       if(n1 = 0)
       {
       fbuf[0x37]= (0x02);
       fbuf[0xB7]= (0x02);

       }

       n2=0;
       if(fbuf[0x08] = 0x00){ n2 = 1; }
       if(n2 = 0)
       {
       fbuf[0x37]= (0x03);
       fbuf[0xB7]= (0x03);

       }

       n3=0;
       if(fbuf[0x0C] = 0x00){ n3 = 1; }
       if(n3 = 0)
       {
       fbuf[0x37]= (0x04);
       fbuf[0xB7]= (0x04);

       }

}






//-------------------proces key-----------

proc show_key1()
{

	var a, b, c, d,i,f, dump_error;
 
 
 dump_error = 0;
 if(fbuf[0xCF] = 0x38){ dump_error = 1; }
 
 
if(dump_error=0){ Page11[0] = 0x0; Page11[1] = 0x0; Page11[2] = 0x0; Page11[3] = 0x0; Page11.color = 0x0000FF; }
if(dump_error=0){ Page12[0] = 0x0; Page12[1] = 0x0; Page12[2] = 0x0; Page12[3] = 0x0; Page12.color = 0x0000FF; }
if(dump_error=0){ Page13[0] = 0x0; Page13[1] = 0x0; Page13[2] = 0x0; Page13[3] = 0x0; Page13.color = 0x0000FF; }
if(dump_error=0){ Page14[0] = 0x0; Page14[1] = 0x0; Page14[2] = 0x0; Page14[3] = 0x0; Page14.color = 0x0000FF; }

if(dump_error = 0)
 {
  lbDumpState = "Ошибка дампа!";
  eeprom_chek = "Ошибка дампа!";
  eeprom_chek.color = 0x0000FF;
 }

else
 {


	Page11[0] = fbuf[0x03];
	Page11[1] = fbuf[0x02];
	Page11[2] = fbuf[0x01];
	Page11[3] = fbuf[0x00];
        Page11.color = 0xFFFFFF;

        Page12[0] = fbuf[0x07];
	Page12[1] = fbuf[0x06];
	Page12[2] = fbuf[0x05];
	Page12[3] = fbuf[0x04];
        Page12.color = 0xFFFFFF;

	Page13[0] = fbuf[0x0B];
	Page13[1] = fbuf[0x0A];
	Page13[2] = fbuf[0x09];
	Page13[3] = fbuf[0x08];
        Page13.color = 0xFFFFFF;

	Page14[0] = fbuf[0x0F];
	Page14[1] = fbuf[0x0E];
	Page14[2] = fbuf[0x0D];
	Page14[3] = fbuf[0x0C];                 
        Page14.color = 0xFFFFFF;                

   lbDumpState = "Damp OK!";
   eeprom_chek = "Damp OK!";
   eeprom_chek.color = 0xFF0000;
 }
}




//----key1---

proc new_key1()
{
   var a,c,d,g,f,dump_error;
 dump_error = 0;
 if(fbuf[0xCF] = 0x38){ dump_error = 1; }
 


if(dump_error = 0)
 {
  lbDumpState = "Ошибка!";
  eeprom_chek = "Ошибка дампа!";
  eeprom_chek.color = 0x0000FF;
if(dump_error=0){ Page11[0] = 0x0; Page11[1] = 0x0; Page11[2] = 0x0; Page11[3] = 0x0; Page11.color = 0x0000FF; }
if(dump_error=0){ Page12[0] = 0x0; Page12[1] = 0x0; Page12[2] = 0x0; Page12[3] = 0x0; Page12.color = 0x0000FF; }
if(dump_error=0){ Page13[0] = 0x0; Page13[1] = 0x0; Page13[2] = 0x0; Page13[3] = 0x0; Page13.color = 0x0000FF; }
if(dump_error=0){ Page14[0] = 0x0; Page14[1] = 0x0; Page14[2] = 0x0; Page14[3] = 0x0; Page14.color = 0x0000FF; }
 }
else
 {

        show_key1();

        a=0;
        c=ReadID();
        if(hbBlock32[0]= 0xFF) {a= 1;}
        if(a= 1)   
       {
       eeprom_chek ="No transponder !";
       eeprom_chek.color=0x0000FF;
       }
 else
 { 
     f=0;
     d=readBlock10();

     if(cbLB0 = 1) {f= 1;}
     if(f= 1)
     {  
        mbox(" Транспондер залочен \n Transponder bad",0);
       eeprom_chek ="Replace transponder!";
       eeprom_chek.color=0x0000FF;
        return;
     }

    else
    {
        c=ReadID();
  

        fbuf[0x03]= hbBlock32[0];
	fbuf[0x02]= hbBlock32[1];
	fbuf[0x01]= hbBlock32[2];
	fbuf[0x00]= hbBlock32[3];

        fbuf[0x83]= hbBlock32[0];
	fbuf[0x82]= hbBlock32[1];
	fbuf[0x81]= hbBlock32[2];
	fbuf[0x80]= hbBlock32[3];

     g=nkey();
     g=cript1();
     g=writeWord9();
     g=writeWord8();
     g=writeWord7();
     g=writeWord6();
     g=writeWord5();
     g=writeWord4();
     

    keychek1 = "Write Key1 complete!";
    eeprom_chek ="Safe NEW Dump !";
    eeprom_chek.color=0x0000FF;
    }
   }
  }
}





//----key2---

proc new_key2()
{
   var a,c,d,g,f,dump_error;
 dump_error = 0;
 if(fbuf[0xCF] = 0x38){ dump_error = 1; }

 
if(dump_error = 0)
 {
  lbDumpState = "Ошибка!";
  eeprom_chek = "Ошибка дампа!";
  eeprom_chek.color = 0x0000FF;
if(dump_error=0){ Page11[0] = 0x0; Page11[1] = 0x0; Page11[2] = 0x0; Page11[3] = 0x0; Page11.color = 0x0000FF; }
if(dump_error=0){ Page12[0] = 0x0; Page12[1] = 0x0; Page12[2] = 0x0; Page12[3] = 0x0; Page12.color = 0x0000FF; }
if(dump_error=0){ Page13[0] = 0x0; Page13[1] = 0x0; Page13[2] = 0x0; Page13[3] = 0x0; Page13.color = 0x0000FF; }
if(dump_error=0){ Page14[0] = 0x0; Page14[1] = 0x0; Page14[2] = 0x0; Page14[3] = 0x0; Page14.color = 0x0000FF; }
 }
else
 {

        show_key1();

        a=0;
        c=ReadID();
        if(hbBlock32[0]= 0xFF) {a= 1;}
        if(a= 1)   
       {
       eeprom_chek ="No transponder !";
       eeprom_chek.color=0x0000FF;
       }
 else
 {
     f=0;
     d=readBlock10();

     if(cbLB0 = 1) {f= 1;}
     if(f= 1)
     {  
        mbox(" Транспондер залочен \n Transponder bad",0);
       eeprom_chek ="Replace transponder!";
       eeprom_chek.color=0x0000FF;
        return;
     }

    else
    {
        c=ReadID();
     

        fbuf[0x07]= hbBlock32[0];
	fbuf[0x06]= hbBlock32[1];
	fbuf[0x05]= hbBlock32[2];
	fbuf[0x04]= hbBlock32[3];

        fbuf[0x87]= hbBlock32[0];
	fbuf[0x86]= hbBlock32[1];
	fbuf[0x85]= hbBlock32[2];
	fbuf[0x84]= hbBlock32[3];


     g=nkey();
     g=cript1();
     g=writeWord9();
     g=writeWord8();
     g=writeWord7();
     g=writeWord6();
     g=writeWord5();
     g=writeWord4();


    keychek2 = "Write Key2 complete!";
    eeprom_chek ="Safe NEW Dump !";
    eeprom_chek.color=0x0000FF;
    }
   }
  }
}




//----key3---

proc new_key3()
{
   var a,c,d,g,f,dump_error;
 dump_error = 0;
 if(fbuf[0xCF] = 0x38){ dump_error = 1; }
 

if(dump_error = 0)
 {
  lbDumpState = "Ошибка!";
  eeprom_chek = "Ошибка дампа!";
  eeprom_chek.color = 0x0000FF;
if(dump_error=0){ Page11[0] = 0x0; Page11[1] = 0x0; Page11[2] = 0x0; Page11[3] = 0x0; Page11.color = 0x0000FF; }
if(dump_error=0){ Page12[0] = 0x0; Page12[1] = 0x0; Page12[2] = 0x0; Page12[3] = 0x0; Page12.color = 0x0000FF; }
if(dump_error=0){ Page13[0] = 0x0; Page13[1] = 0x0; Page13[2] = 0x0; Page13[3] = 0x0; Page13.color = 0x0000FF; }
if(dump_error=0){ Page14[0] = 0x0; Page14[1] = 0x0; Page14[2] = 0x0; Page14[3] = 0x0; Page14.color = 0x0000FF; }
 }
else
 {

        show_key1();

        a=0;
        c=ReadID();
        if(hbBlock32[0]= 0xFF) {a= 1;}
        if(a= 1)   
       {
       eeprom_chek ="No transponder !";
       eeprom_chek.color=0x0000FF;
       }
 else
 {
     f=0;
     d=readBlock10();

     if(cbLB0 = 1) {f= 1;}
     if(f= 1)
     {  
        mbox(" Транспондер залочен \n Transponder bad",0);
       eeprom_chek ="Replace transponder!";
       eeprom_chek.color=0x0000FF;
        return;
     }

    else
    {
        c=ReadID();
    

        fbuf[0x0B]= hbBlock32[0];
	fbuf[0x0A]= hbBlock32[1];
	fbuf[0x09]= hbBlock32[2];
	fbuf[0x08]= hbBlock32[3];

        fbuf[0x8B]= hbBlock32[0];
	fbuf[0x8A]= hbBlock32[1];
	fbuf[0x89]= hbBlock32[2];
	fbuf[0x88]= hbBlock32[3];
         

        g=nkey();
        g=cript1();
        g=writeWord9();
        g=writeWord8();
        g=writeWord7();
        g=writeWord6();
        g=writeWord5();
        g=writeWord4();

    keychek3 = "Write Key3 complete!";
    eeprom_chek ="Safe NEW Dump !";
    eeprom_chek.color=0x0000FF;
    }
   }
  }
}






//----key4---

proc new_key4()
{
   var a,c,d,g,f,dump_error;
 dump_error = 0;
 if(fbuf[0xCF] = 0x38){ dump_error = 1; }
 

if(dump_error = 0)
 {
  lbDumpState = "Ошибка!";
  eeprom_chek = "Ошибка дампа!";
  eeprom_chek.color = 0x0000FF;
if(dump_error=0){ Page11[0] = 0x0; Page11[1] = 0x0; Page11[2] = 0x0; Page11[3] = 0x0; Page11.color = 0x0000FF; }
if(dump_error=0){ Page12[0] = 0x0; Page12[1] = 0x0; Page12[2] = 0x0; Page12[3] = 0x0; Page12.color = 0x0000FF; }
if(dump_error=0){ Page13[0] = 0x0; Page13[1] = 0x0; Page13[2] = 0x0; Page13[3] = 0x0; Page13.color = 0x0000FF; }
if(dump_error=0){ Page14[0] = 0x0; Page14[1] = 0x0; Page14[2] = 0x0; Page14[3] = 0x0; Page14.color = 0x0000FF; }
 }
else
 {

        show_key1();

        a=0;
        c=ReadID();
        if(hbBlock32[0]= 0xFF) {a= 1;}
        if(a= 1)   
       {
       eeprom_chek ="No transponder !";
       eeprom_chek.color=0x0000FF;
       }
 else
 {
     f=0;
     d=readBlock10();

     if(cbLB0 = 1) {f= 1;}
     if(f= 1)
     {  
        mbox(" Транспондер залочен \n Transponder bad",0);
       eeprom_chek ="Replace transponder!";
       eeprom_chek.color=0x0000FF;
        return;
     }

    else
    {
        c=ReadID();
    

        fbuf[0x0F]= hbBlock32[0];
	fbuf[0x0E]= hbBlock32[1];
	fbuf[0x0D]= hbBlock32[2];
	fbuf[0x0C]= hbBlock32[3];

        fbuf[0x8F]= hbBlock32[0];
	fbuf[0x8E]= hbBlock32[1];
	fbuf[0x8D]= hbBlock32[2];
	fbuf[0x8C]= hbBlock32[3];
         

        g=nkey(); 
        g=cript1();
        g=writeWord9();
        g=writeWord8();
        g=writeWord7();
        g=writeWord6();
        g=writeWord5();
        g=writeWord4();


    keychek4 = "Write Key4 complete!";
    eeprom_chek ="Safe NEW Dump !";
    eeprom_chek.color=0x0000FF;
    }
   }
  }
}




//-------------CHECK KEY-------------



proc view_key()
{
 Var a,b,c,i,error;

        a=0;
        c=ReadID();
        if(hbBlock32[0]= 0xFF) {a= 1;}
        if(a= 1)   
       {
       eeprom_chek ="No transponder !";
       eeprom_chek.color=0x0000FF;
       return;
       }

     c=ReadID();


    error = 0;

//------------
    for(i = 0x01; i < 0x02; i++)
    {
        if(hbBlock32[0] != fbuf[0x03]) error = 1;
        if(hbBlock32[1] != fbuf[0x02]) error = 1;
        if(hbBlock32[2] != fbuf[0x01]) error = 1;
        if(hbBlock32[3] != fbuf[0x00]) error = 1;
    }
    if(error != 1)
    {
        print("\n Ключ 1");
        mbox(" Ключ 1 \n Key 1",0);
        return;
    }

//------------
    for(i = 0x01; i < 0x02; i++)
    {
        if(hbBlock32[0] != fbuf[0x07]) error = 2;
        if(hbBlock32[1] != fbuf[0x06]) error = 2;
        if(hbBlock32[2] != fbuf[0x05]) error = 2;
        if(hbBlock32[3] != fbuf[0x04]) error = 2;
    }
    if(error != 2)
    {

        print("\n Ключ 2");
        mbox(" Ключ 2 \n Key 2",0);
        return;
    }

//------------
    for(i = 0x01; i < 0x02; i++)
    {
        if(hbBlock32[0] != fbuf[0x0B]) error = 3;
        if(hbBlock32[1] != fbuf[0x0A]) error = 3;
        if(hbBlock32[2] != fbuf[0x09]) error = 3;
        if(hbBlock32[3] != fbuf[0x08]) error = 3;
    }
    if(error != 3)
    {

        print("\n Ключ 3");
        mbox(" Ключ 3 \n Key 3",0);
        return;
    }

//------------
    for(i = 0x01; i < 0x02; i++)
    {
        if(hbBlock32[0] != fbuf[0x0F]) error = 4;
        if(hbBlock32[1] != fbuf[0x0E]) error = 4;
        if(hbBlock32[2] != fbuf[0x0D]) error = 4;
        if(hbBlock32[3] != fbuf[0x0C]) error = 4;
    }
    if(error != 4)
    {

        print("\n Ключ 4");
        mbox(" Ключ 4 \n Key 4",0);
        return;
    }

    if(error != 0)
    {
        print("\nThe key is not of this immo!");
        mbox("Ключ не от етого иммо! \nThe key is not of this immo!",0);
        return;
    }
}






proc c(){}
//====================================================================================
$DEVICE

#define DIN_H   PORTB |= (1<<5)
#define DIN_L   PORTB &= ((1<<5)^255)
#define SCLK_H  PORTB |= (1<<6)
#define SCLK_L  PORTB &= ((1<<6)^255)

#define DOUT_H  (PORTB & (1<<4)) != 0
#define DOUT_L  (PORTB & (1<<4)) = 0
#define DOUT_IN (PORTB & (1<<4))

#define SET_CONFIG_PAGE 	0x40
#define GET_CONFIG_PAGE 	0x04
#define WRITE_TAG       	0xC0
#define WRITE_TAG_N     	0x10
#define	READ_PHASE			0x08
#define	SET_SAMPLING_TIME	0x80

#define	FST_TMR_PER_T0	48			// Увеличение счетчика FAST_TIMER за время T0, при 

dword	dbgu[1000];
dword	dbg_n;
dword	dbg_timer;

dword	tag_data;

byte	sData[1000];
dword	sLen;
byte	dec_st;

//******************************** Megamos48 ************************************//

proc status()
{
	return(POWER & 1);
}

proc pwr(a)
{
    PWM0 = 0;
    POWER = a;
    if(a)   PWM0 = (4000000 << 7) | 64;
}

// отправка команды в трансивер
proc HTRCCmd(cmd)
{
    var i, cnt, mem;

    DIN_L; SCLK_L; SCLK_H; DIN_H; SCLK_L; DIN_L;    // инициализация
    
    if((cmd & 0xC0) = 0xC0) cnt = 3;        // если два старших бита команды установлены, то команда трехбитная
    else cnt = 8;

    mem = cmd & 0xF0;

    for(i = 0 ; i < cnt;i++)
    {
        if(cmd & 0x80)    DIN_H;
        else              DIN_L;
        SCLK_H; SCLK_L;
        cmd = cmd << 1;
    }
    DIN_L; 
    if(cnt = 3) return;  
    if(mem = 0)                         // если старшие 4 бита команды равны нулю, то команда имеет ответ
    {
        for(i = 0; i < 8; i++)
        {
            SCLK_H;
            cmd = cmd << 1;
            if(DOUT_H)  cmd |= 1;
            SCLK_L;
        }
        return(cmd & 255);
    }
}

// инициализация трансивера 
proc InitHTRC()
{
    var a;

	HTRCcmd(SET_CONFIG_PAGE + 0x00 + 0x02);
	HTRCcmd(SET_CONFIG_PAGE + 0x10 + 0x00);
	HTRCcmd(SET_CONFIG_PAGE + 0x20 + 0x00);
	HTRCcmd(SET_CONFIG_PAGE + 0x30 + 0x00);
	// читаем обратно нулевую страницу, чтобы проверить связь с трансивером
	a = HTRCcmd(GET_CONFIG_PAGE + 0x00);  if((a & 0x0F) != 0x02)	return (1);
	//a = HTRCcmd(GET_CONFIG_PAGE + 0x01);  if((a & 0x0F) != 0x00)	return (1);

	return (0);
}

proc Restart_Transponder()
{
	HTRCcmd(SET_CONFIG_PAGE + 0x10 + 0x01);		// switch off HTRC110 drivers/RF-field
	Delay(10000);
	HTRCcmd(SET_CONFIG_PAGE + 0x10 + 0x0);		// switch on HTRC110 drivers again
	Delay(2000);
	
	return (1);
}

proc Ast_Adjust(offset)
{
	var a;

	a = HTRCcmd(READ_PHASE);
	a = (a << 1);
	a = (a + offset);
	a = (a & 0x3F);
	HTRCcmd(SET_SAMPLING_TIME | a);
	
	return (1);
}

proc InitFastTimer()
{
	FAST_TIMER_CLOCK = 1;		// 6 МГц
}

proc InitCapture()
{
	var	a;
	
	// READ_TAG
	HTRCcmd(0x6A);
    HTRCcmd(0x6B);
    HTRCcmd(0x60);
    HTRCcmd(0xE0);
	
	//SET UP INTERVALS
    CAPT_INTERVAL0 = (4 << 16) | 8;           // 16To = 128mkc = 128/21.33 = 6.000
    CAPT_INTERVAL1 = (9 << 16) | 14;          // 32To = 256mkc = 256/21.33 = 12.000
	CAPT_INTERVAL2 = (14 << 16) | 21;           // 48To = 128mkc = 128/21.33 = 6.000
    CAPT_INTERVAL3 = (21 << 16) | 28;         // 64To = 512mkc = 512/21.33 = 24.000
    CAPT_INTERVAL4 = 0xFF;
	CAPT_INTERVAL5 = 0xFF;
	CAPT_INTERVAL6 = 0xFF;
	CAPT_INTERVAL7 = 0xFF;	
	
	//INIT CAPTURE MODE
    CAPT_MODE = 0;
    CAPT_CLOCK = 4;
	
	//dec_st = 0;
	
    IRQ_ENABLE = 1;		// разрешаем прерывание
}

proc DeInitCapture()
{
	IRQ_ENABLE = 0;
}

proc SearchLIW()	// 16 64 32 48
{
	var a, p, guard, result;
	
	
	dbg_n = 0;
	guard = 0;
	result = 0;
	dec_st = 0;
	
	a = IRQ_FLAG;	// Сбрасываем флаг прерывания!!!
	
	for(;;)
	{
		guard++;
		if(guard = 5000){ dec_st = 0; break; }
		if(IRQ_FLAG = 0) continue;
		
		p = CAPT_VALUE2 & 0x7F;
	
		dbgu[dbg_n] = p;
		dbg_n++;
	
		//continue;
		if(dec_st = 0)		// Wait 32 pulse
		{
			if(p = 1){ dec_st = 1; continue; }	// 32 pulse
			continue;
		}
		if(dec_st = 1)		// Wait 48 pulse
		{
			if(p = 1){ dec_st = 1; continue; }
			if(p = 2){ dec_st = 2; continue; }
			dec_st = 0; continue;
		}
		if(dec_st = 2)		// Wait 16 pulse
		{
			if(p = 0){ dec_st = 3; continue; }	// 16 pulse
			if(p = 1){ dec_st = 1; continue; }	// 32 pulse
			dec_st = 0; continue;
		}
		if(dec_st = 3)		// Wait 64 pulse
		{
			if(p = 1){ dec_st = 1; continue; }
			if(p = 3){ result = 1; break; }
			dec_st = 0; continue;
		}
	}
	
	FAST_TIMER = 0;
	
	return (result);
}

proc Read32BitManch()
{
	var a, p, t, guard, result, level, bt_cnt;
	

	dbg_n = 0;
	guard = 0;
	result = 0;
	bt_cnt = 0;
	dec_st = 0;
	level = 0;
	tag_data = 0;
	
	// Wait
	t = 171 * FST_TMR_PER_T0;	// Откалибровано!!! Сейчас от 164 до 178.
	while(FAST_TIMER < t);
	a = IRQ_FLAG;				// перед началом сбрасываем флаг прерывания
	a = 0;
	
	for(;;)
	{
		guard++;
		if(guard = 2000){ dec_st = 0; break; }
		if(IRQ_FLAG = 0) continue;
		
		p = CAPT_VALUE2 & 0x7F;
	
		dbgu[dbg_n] = p;
		dbg_n++;
		//continue;
		// Read Header
		if(dec_st = 0)	// читаем еденицы
		{
			if(p = 0)
			{
				a++; if(a = 15){ a = 0; dec_st = 1; } continue;
			}
			break;
		}
		if(dec_st = 1)	// переход на нули
		{
			if(p = 1){ dec_st = 2; continue; }
			break;
		}
		if(dec_st = 2)	// читаем нули
		{
			if(p = 0)
			{
				a++; if(a = 6){ a = 0; dec_st = 3; } continue;
			}
			break;
		}
		if(dec_st = 3)	// переход на данные
		{
			if(p = 0){ dec_st = 4; continue; }
			if(p = 1){ level ^= 1; dec_st = 5; continue; }
			break;
		}
		
		// Read Data
		if(dec_st = 4)	// Wait Short Interval
		{
			if(p = 0)	// Short Interval
			{
				if(bt_cnt = 31){ tag_data = ((tag_data << 1) | level); result = 1; break; }
				else{ dec_st = 5; continue; }
			}
			break;
		}
		if(dec_st = 5)	// Wait Any Interval
		{
			if(p = 0)	// Short Interval
			{
				tag_data = ((tag_data << 1) | level); bt_cnt++; dec_st = 4; continue;
			}
			if(p = 1)	// Long	Interval
			{
				tag_data = ((tag_data << 1) | level); level ^= 1; bt_cnt++;
				if(bt_cnt = 31){ tag_data = ((tag_data << 1) | level); result = 1; break; }
				else{ dec_st = 5; continue; }
			}
			break;
		}
	}
	
	FAST_TIMER = 0;
	
	return (result);
}

proc EncodeBits(Bits, Num)		
{
	var i;
	
	i = 0;
	while(i != Num)
	{
		if(Bits & 0x80000000){ sData[sLen] = 0x0; }
		else{ sData[sLen] = 0x70; }
		
		sLen++;
		Bits = Bits << 1;
		i++;
	}
}

proc ReadBlock(block)	// block 0 - User Memory, block 1 - ID 
{
	var a, t;
	
	// PreInit
	STREAMPIN = PORTB.5;
	sLen = 0;
	
	// Prepare Stream
	if(block = 0)
	{
		EncodeBits(0x14000000, 6);		// Генерируем команду чтение UM блока
	}
	else
	{
		EncodeBits(0x0C000000, 6);		// Генерируем команду чтения ID блока
	}
	
	InitCapture();
	a = SearchLIW();
	if(a = 0){ DeInitCapture(); return (0); }
	DeInitCapture();
	
	// WRITE_TAG( прозрачный режим )
	HTRCcmd(0xC0);
	DIN_L;
	
	
	// Wait
	t = 110 * FST_TMR_PER_T0;	// Откалибровано!!! Сейчас от 100 до 130.
	while(FAST_TIMER < t);
	
	a = sLen * 8;
	StreamOut(sData, a, 32);
	FAST_TIMER = 0;
	
	
	InitCapture();
	dbg_timer = FAST_TIMER;
	dbg_timer = dbg_timer / FST_TMR_PER_T0;
	a = Read32BitManch();
	//a = SearchLIW();
	if(a = 0){ DeInitCapture(); return (0); }
	DeInitCapture();
	//dbg_timer = dbg_timer / FST_TMR_PER_T0;
	return (1);
	
}

proc EncodeBitsWithParity(Bits, Num)		
{
	var i, parity;
	
	parity = 0;
	i = 0;
	while(i != Num)
	{
		parity = parity ^ Bits;
		if(Bits & 0x80000000){ sData[sLen] = 0x0; }
		else{ sData[sLen] = 0x70; }
		
		sLen++;
		Bits = Bits << 1;
		i++;
	}
	
	parity = parity & 0x80000000;
	if(parity = 0x80000000){ sData[sLen] = 0x0; }
	else{ sData[sLen] = 0x70; }
	sLen++;
}

proc EncodeWriteCmd(Adr, HByte, LByte)
{
	var i, data, cparity;
	
	EncodeBits(0x28000000, 6);	// Генерируем команду записи слова
	
	Adr = ((Adr & 0xF) << 28);
	EncodeBitsWithParity(Adr, 4);
	
	data = (((HByte & 0xFF) << 24) | ((LByte & 0xFF) << 16));
	tag_data = data;
	
	cparity = 0;
	i = 0;
	while(i != 4)
	{
		cparity = cparity ^ data;
		EncodeBitsWithParity(data, 4);
		data = data << 4;
		i++;
	}
	
	cparity = cparity & 0xF0000000;
	EncodeBits(cparity, 5);
}

proc CheckACK()	// 16 16 48 16 48 16
{
	var a, p, guard, result;
	
	dbg_n = 0;
	guard = 0;
	result = 0;
	dec_st = 0;
	
	a = IRQ_FLAG;	// Сбрасываем флаг прерывания!!!
	
	for(;;)
	{
		guard++;
		if(guard = 5000){ dec_st = 0; break; }
		if(IRQ_FLAG = 0) continue;
		
		p = CAPT_VALUE2 & 0x7F;
	
		dbgu[dbg_n] = p;
		dbg_n++;
	
		if(dec_st = 0)	// ждем импульс 16 * t0
		{
			if(p = 0){ dec_st = 1; continue; }	// импульс 16 * t0
			break;	// ошибка
		}
		if(dec_st = 1)	// ждем импульс 48 * t0
		{
			if(p = 2){ dec_st = 2; continue; }	// импульс 48 * t0
			break;	// ошибка
		}
		if(dec_st = 2)	// ждем импульс 16 * t0
		{
			if(p = 0){ dec_st = 3; continue; }	// импульс 16 * t0
			break;	// ошибка
		}
		if(dec_st = 3)	// ждем импульс 48 * t0
		{
			if(p = 2){ dec_st = 4; continue; }	// импульс 48 * t0
			break;	// ошибка
		}
		if(dec_st = 4)	// ждем импульс 16 * t0
		{
			if(p = 0){ result = 1; break; }	// импульс 16 * t0
			break;	// ошибка
		}
	}
	
	FAST_TIMER = 0;
	
	return (result);
}

proc WriteWord(Adr, HByte, LByte)
{
	var a, t;
	
	// PreInit
	STREAMPIN = PORTB.5;
	sLen = 0;
	EncodeWriteCmd(Adr, HByte, LByte);
	
	InitCapture();
	a = SearchLIW();
	if(a = 0){ DeInitCapture(); return (0); }
	DeInitCapture();
	
	// WRITE_TAG( прозрачный режим )
	HTRCcmd(0xC0);
	DIN_L;
	
	// Wait
	t = 113 * FST_TMR_PER_T0;	// Откалибровано!!! Сейчас от 100 до 130.
	while(FAST_TIMER < t);
	
	a = sLen * 8;
	StreamOut(sData, a, 32);
	FAST_TIMER = 0;
	
	
	InitCapture();
	// Wait
	t = 183 * FST_TMR_PER_T0;	// Откалибровано!!! Сейчас от 176 до 192.
	while(FAST_TIMER < t);
	
	a = CheckACK();
	if(a = 0){ DeInitCapture(); return (0); }
	DeInitCapture();
	
	// Wait
	delay(25000);
	
	return (1);
}