unit Unit1;
   
interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, StdCtrls, ComCtrls, IniFiles, Boots,
  ModuleLoader, Base64, clipbrd, Registry, Masks, strutils, ExtCtrls,
  HexUtils, UsbMain, UnitAndrey, UnitPavel, Mask, UnitMisc, Gauges, Buttons,
  TntStdCtrls, ComPort, FileCtrl, TntComCtrls, TntForms, Fboots, CardEx, xCrypt,
  DCPcrypt2, DCPsha1, DCPblockciphers, DCPdes, DateUtils, ShlObj, ShellCtrls,
  uTokens, DCPmd5, ShellAPI, RplDecode, CoolTrayIcon, D2XXUnit, UnitUFS, uPPMLang, Ucontent, DCPrijndael;

type
TSetServerIp = function (srvurl:PChar):integer; stdcall;
type
TCallServer = function (imei,log,pass:PChar;rap,key,hash,data:pointer;data_ln:integer;pm1,pm2,pm3:pointer;s_ver,r_dat,crd:PChar;mode:integer):integer;stdcall;
//type
//TAsk2Rpl = function (log,pass:PChar;rap,key,hash,data:pointer;data_ln:integer;s_ver:PChar;pm1,pm2:pointer;pm2_l:integer;pm3:pointer;crd:PChar):integer;stdcall;

type
  TForm1 = class(TForm)
    mm1: TMainMenu;
    Settings1: TMenuItem;
    Connectsettings1: TMenuItem;
    pgc1: TPageControl;
    ts1: TTabSheet;
    ts2: TTabSheet;
    grp1: TGroupBox;
    statusbar: TStatusBar;
    ts3: TTabSheet;
    TimOfClock: TTimer;
    TimConChk: TTimer;
    pm1: TPopupMenu;
    Copyinfo1: TMenuItem;
    clearlog1: TMenuItem;
    grpMain: TGroupBox;
    grpUserCode: TGroupBox;
    grpProductCode: TGroupBox;
    PrdEdit: TEdit;
    ASKRPLgrp: TGroupBox;
    GrPmOper: TGroupBox;
    FullPMRad: TRadioButton;
    RangePMRad: TRadioButton;
    PmFromEd: TMaskEdit;
    PmToEd: TMaskEdit;
    Label1: TLabel;
    Label2: TLabel;
    GrPhMode: TGroupBox;
    CBoxSetMode: TComboBox;
    LifeTimergrp: TGroupBox;
    LTHedt: TEdit;
    LTMedt: TEdit;
    Hlbl: TLabel;
    Mlbl: TLabel;
    SaveDialog: TSaveDialog;
    FactorySetgrp: TGroupBox;
    FullFactorychk: TCheckBox;
    UserDatachk: TCheckBox;
    Swupgrdefchk: TCheckBox;
    ServiceCentrechk: TCheckBox;
    PrdTunechk: TCheckBox;
    LeaveFactorychk: TCheckBox;
    OpenDialog: TOpenDialog;
    pb1: TGauge;
    InfoRdBtn: TBitBtn;
    ReadPmBtn: TBitBtn;
    WritePmBtn: TBitBtn;
    GetUcodebtn: TBitBtn;
    ResetUcodebtn: TBitBtn;
    SetModeBtn: TBitBtn;
    ReadAskbtn: TBitBtn;
    ReadLTbtn: TBitBtn;
    ResetLTbtn: TBitBtn;
    WriteLTbtn: TBitBtn;
    ReadPrCodebtn: TBitBtn;
    WritePrdbtn: TBitBtn;
    DoFSetbtn: TBitBtn;
    GroupBox1: TGroupBox;
    ReadPPBtn: TBitBtn;
    WritePPBtn: TBitBtn;
    GroupBox2: TGroupBox;
    ExtPhbBtn: TBitBtn;
    WritePBbtn: TBitBtn;
    GroupBox3: TGroupBox;
    Calendarbtn: TBitBtn;
    GroupBox5: TGroupBox;
    SDpassbtn: TBitBtn;
    lst1: TTntListBox;
    grpMiscTool: TGroupBox;
    Formatgrp: TGroupBox;
    DoFormatbtn: TBitBtn;
    grpADCreadings: TGroupBox;
    btnADCread: TBitBtn;
    grpTesting: TGroupBox;
    btnInit: TBitBtn;
    grpunlock: TGroupBox;
    edtNCK: TEdit;
    btnNCKenter: TBitBtn;
    lblNCK: TLabel;
    USB1: TMenuItem;
    COM1: TMenuItem;
    GroupBox6: TGroupBox;
    PatternCbox: TComboBox;
    Patt: TLabel;
    SetPatternbtn: TBitBtn;
    btnWriteCalendar: TBitBtn;
    TimLic: TTimer;
    Exit1: TMenuItem;
    cbbLevel: TComboBox;
    lblncklev: TLabel;
    DCP_3des1: TDCP_3des;
    DCP_sha11: TDCP_sha1;
    tsFlashing: TTabSheet;
    grpFLsel: TGroupBox;
    MCUt: TEdit;
    PPMt: TEdit;
    CNTt: TEdit;
    APEt: TEdit;
    grpFLset: TGroupBox;
    chkDEADMODE: TCheckBox;
    chkBackup: TCheckBox;
    grpAfterFlash: TGroupBox;
    chkDOWNGRADE: TCheckBox;
    GroupBox4: TGroupBox;
    SaUsAr: TBitBtn;
    btnFLASH: TBitBtn;
    Mainsettings1: TMenuItem;
    GroupBox7: TGroupBox;
    RdSms: TBitBtn;
    Copyselected1: TMenuItem;
    pbsm1: TGauge;
    chkPPMe: TCheckBox;
    chkCNTe: TCheckBox;
    chkAPEe: TCheckBox;
    FlMan: TCheckBox;
    UsIni: TCheckBox;
    Modelsel: TComboBox;
    cbbSelPC: TComboBox;
    chkMCUen: TCheckBox;
    mcub: TButton;
    cntb: TButton;
    apeb: TButton;
    grpStuff: TGroupBox;
    btnKeyBTest: TBitBtn;
    btnFunLabel: TBitBtn;
    sk308: TCheckBox;
    PPM1t: TEdit;
    chkPPM1e: TCheckBox;
    ppmb: TButton;
    ppm1b: TButton;
    Cnt3t: TEdit;
    chkCnt3: TCheckBox;
    cnt3b: TButton;
    N1: TMenuItem;
    N0: TMenuItem;
    N2: TMenuItem;
    ch: TMenuItem;
    N3: TMenuItem;
    UserIn: TCheckBox;
    Label3: TLabel;
    btnSvUsIni: TBitBtn;
    BitBtn1: TBitBtn;
    DCP_md51: TDCP_md5;
    cltrycn: TCoolTrayIcon;
    RPLrew: TGroupBox;
    btnWriteRPL: TBitBtn;
    btnReadRPL: TBitBtn;
    chkSimlock: TCheckBox;
    chkSD: TCheckBox;
    chkStufCert: TCheckBox;
    chkErNPC: TCheckBox;
    chkErCC: TCheckBox;
    chkerHWC: TCheckBox;
    rbCertWrite: TRadioButton;
    rbCrtErase: TRadioButton;
    grp2: TGroupBox;
    grpS40LowFormat: TGroupBox;
    cbbLFmdel: TComboBox;
    btnFormatS40LowLevel: TBitBtn;
    grpDCC: TGroupBox;
    btnCamCheck: TBitBtn;
    btnReadCamConf: TBitBtn;
    chkCLMA: TCheckBox;
    cbbModeFlash: TComboBox;
    grpFlashModesettings: TGroupBox;
    chkReseLT: TCheckBox;
    chkBootNormal: TCheckBox;
    chkAFFset: TCheckBox;
    chkCheckRead: TCheckBox;
    chkChPC: TCheckBox;
    GroupBox8: TGroupBox;
    UplJ: TBitBtn;
    ChUnl: TBitBtn;
    SrvEd: TEdit;
    Label4: TLabel;
    GroupBox9: TGroupBox;
    SlxU: TBitBtn;
    GroupBox10: TGroupBox;
    LsxB: TBitBtn;
    chkWrKeyAll: TCheckBox;
    CheckBox1: TCheckBox;
    csvch: TCheckBox;
    RepUnlT: TTabSheet;
    RSDD: TBitBtn;
    RdUniKey: TBitBtn;
    custk: TCheckBox;
    btnSx4UplTune: TBitBtn;
    RepSLb: TBitBtn;
    CbLnck: TCheckBox;
    suppar: TComboBox;
    btnWriteMsg: TBitBtn;
    chkPackread: TCheckBox;
    checkbtn: TBitBtn;



    procedure FormCreate(Sender: TObject);
    procedure TimConChkTimer(Sender: TObject);
    procedure TimOfClockTimer(Sender: TObject);
    procedure InfoRdBtnClick(Sender: TObject);
    procedure clearlog1Click(Sender: TObject);
    procedure Copyinfo1Click(Sender: TObject);
    procedure SltestToClipboard(buffersize:integer);
    procedure checkbtnClick(Sender: TObject);
    procedure ResetUCodebtnClick(Sender: TObject);
    procedure ReadPrCodebtnClick(Sender: TObject);
    procedure WritePrdbtnClick(Sender: TObject);
    procedure ReadASKbtnClick(Sender: TObject);
    procedure FullPMRadClick(Sender: TObject);
    procedure RangePMRadClick(Sender: TObject);
    procedure SetModeBtnClick(Sender: TObject);
    procedure ReadPmBtnClick(Sender: TObject);
    procedure ResetLTbtnClick(Sender: TObject);
    procedure ReadLTbtnClick(Sender: TObject);
    procedure GetUcodebtnClick(Sender: TObject);
    procedure DoFSetbtnClick(Sender: TObject);
    procedure ExtPhbBtnClick(Sender: TObject);
    procedure WritePmBtnClick(Sender: TObject);
    procedure WriteLTbtnClick(Sender: TObject);
    procedure CalendarbtnClick(Sender: TObject);
    procedure SDpassbtnClick(Sender: TObject);
    procedure ReadPPBtnClick(Sender: TObject);
    procedure WritePPBtnClick(Sender: TObject);
    procedure WriteRPLbtnClick(Sender: TObject);
    procedure btnADCreadClick(Sender: TObject);
    procedure tmClick(Sender: TObject);
    procedure DoFormatbtnClick(Sender: TObject);
    procedure btnNCKenterClick(Sender: TObject);
    procedure WritePBbtnClick(Sender: TObject);
    procedure USB1Click(Sender: TObject);
    procedure COM1Click(Sender: TObject);
    procedure btnInitClick(Sender: TObject);
    procedure SetPatternbtnClick(Sender: TObject);
    procedure btnWriteCalendarClick(Sender: TObject);
    procedure btnLightClick(Sender: TObject);
    procedure TimLicTimer(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Exit1Click(Sender: TObject);
    procedure SelMCUClick(Sender: TObject);
    procedure btnFLASHClick(Sender: TObject);
    procedure selPPMClick(Sender: TObject);
    procedure bselCNTClick(Sender: TObject);
    procedure SaUsArClick(Sender: TObject);
    procedure btnUSEiniClick(Sender: TObject);
    procedure RdSmsClick(Sender: TObject);
    procedure Copyselected1Click(Sender: TObject);
    procedure btnWriteRPLClick(Sender: TObject);
    procedure ModelselChange(Sender: TObject);
    procedure UsIniClick(Sender: TObject);
    procedure mcubClick(Sender: TObject);
    procedure ppmbClick(Sender: TObject);
    procedure cntbClick(Sender: TObject);
    procedure apebClick(Sender: TObject);
    procedure FlManClick(Sender: TObject);
    procedure cbbSelPCChange(Sender: TObject);
    procedure chkDEADMODEClick(Sender: TObject);
    procedure btnKeyBTestClick(Sender: TObject);
    procedure btnFunLabelClick(Sender: TObject);
    procedure s40smsClick(Sender: TObject);
    procedure S60flash;
    procedure ppm1bClick(Sender: TObject);
    procedure Filepresent;
    procedure testnrClick(Sender: TObject);
    procedure btnCamConfClick(Sender: TObject);
    procedure cnt3bClick(Sender: TObject);
    procedure N0Click(Sender: TObject);
    procedure N1Click(Sender: TObject);
    procedure N2Click(Sender: TObject);
    procedure chClick(Sender: TObject);
    procedure btnSvUsIniClick(Sender: TObject);
    procedure UserInClick(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure BitBtn1Click(Sender: TObject);
    procedure cltrycnClick(Sender: TObject);
    procedure btnReadRPLClick(Sender: TObject);
    procedure BUsCheck();
    procedure BUsCheckCMTonly();
    procedure btnUFSconnectClick(Sender: TObject);
    procedure btnPartitionClick(Sender: TObject);
    procedure btnSmlkClick(Sender: TObject);
    procedure btnGrabFSClick(Sender: TObject);
    procedure btnClearFSClick(Sender: TObject);
    procedure btnReadUniqDataClick(Sender: TObject);
    procedure UFSFlashing;
    procedure rbCertWriteClick(Sender: TObject);
    procedure rbCrtEraseClick(Sender: TObject);
    procedure btnRdMessClick(Sender: TObject);
    procedure btnCamCheckClick(Sender: TObject);
    Procedure writeRpl(imei:string);
    procedure btnFormatS40LowLevelClick(Sender: TObject);
    procedure EnUfsbutton();
    procedure DisUfsButton();
    procedure btnReadCamConfClick(Sender: TObject);
    procedure btnInfineOnParseClick(Sender: TObject);
    procedure btnBinfClick(Sender: TObject);
    procedure cbbModeFlashChange(Sender: TObject);
    procedure PPMtClick(Sender: TObject);
    procedure PPM1tClick(Sender: TObject);
    procedure SlxUClick(Sender: TObject);
    procedure ChUnlClick(Sender: TObject);
    procedure FselectFlashMode();
    procedure UplJClick(Sender: TObject);
    procedure LsxBClick(Sender: TObject);
    procedure CncJClick(Sender: TObject);
    procedure chkWrKeyAllClick(Sender: TObject);
    procedure RSDDClick(Sender: TObject);
    procedure RdUniKeyClick(Sender: TObject);
    procedure btnSx4UplTuneClick(Sender: TObject);
    procedure btnReadPPMcatClick(Sender: TObject);
    procedure btnRdFeppClick(Sender: TObject);
    procedure btnWriteMsgClick(Sender: TObject);
    procedure btn333Click(Sender: TObject);
    procedure RepSLbClick(Sender: TObject);
    //procedure btn1Click(Sender: TObject);
  private
procedure DeCriptB8(Buf:pointer);
procedure EncryptF(strmInput,strmOutput:TStream;key:string);
procedure DecryptF(strmInput,strmOutput:TStream;key:string);
function Min(a, b: integer): integer;
function  support_area_access(const download_area_link: string; const product_key: string; extra_url: string = ''): string;
function dcp_hash_md5(const data: string): string;
    { Private declarations }
  public
procedure DisconnectFill();  //тута вырубаем все кнопки
procedure ConnectFill();  //тута врубаем все кнопки
procedure BtnDisable();  //тута вырубаем все кнопки
procedure BtnEnable();  //тута врубаем все кнопки
procedure SetBuzy;  //тута вырубаем все кнопки
function  SetReady:string;  //тута врубаем все кнопки
procedure SetMode(mode:string);
procedure _msg(s:String);
procedure InitSgSt(row:integer);
procedure afterFlashdo();
procedure SilentGetS40FileList(FL:TStrings;path:string);
procedure GetS40FileList(FL:TStrings;path:string);
procedure GetS60FileList(FL:TStrings;path:string);
function RightFileName(const FileName: string):string;
procedure ListBoxToClipboard(buffersize:integer);
procedure SelectFiles();
procedure SearchVpl();
procedure SelCoMode(mode:integer);
procedure WD2ExtractPhoneBook();
procedure prereadstuff();
procedure OmapBootFlash;
procedure WD2RepairPhoneBook();
procedure enableFLtab;
procedure disableFLtab;
function PrdCh(Dir:string):string;
procedure ChPrdD();
function dat2hstr(const s: string; len: dword = 0): string;
procedure ReadDataType(datatype:string ; Dtapath:string; imagenameL:string);
//procedure MyImageWriter(Vimage:string; Bool:boolean);
function AESDecrypt(SourceStream:TStream; DestStream:TStream; key:pointer;IV_in:pointer): Boolean;
function AESEncrypt(SourceStream:TStream; DestStream:TStream; key:pointer): Boolean;
procedure InfLockInfineon();
    { Public declarations }
  end;

var
  Form1                  : TForm1;
  flag                   : Boolean;
  IniFile                : TMemIniFile;
  status,LicExists,good  : Boolean;
  PHName,crpass          : string;
  UserId,fullid,UidSrv,UidPas : string;
  core, ppm, ppm1,
  image, ape,cnt3        : String;
  Phoenixfolder,logfn,
  key                    : string;
  VplList                : TStrings;
  oldsmart               : Boolean;
  OMAP1610               : TMemoryStream;
  TDt                    : TDateTime;
  MC: TMemoryStream;
  stm:integer;
  phsel:integer;
  prd1,prd2,prd3,tphpach:string;
  PhonePresentmode       : Byte;
  npc,hwc,ccc,sld,sdd,
  randd, variantcert,
  apenpc,apehwc,apecc,apevar : WideString;
 SetServerIp: TSetServerIp;
 CallServer: TCallServer;
// Ask2Rpl: TAsk2Rpl;
   hndDLLHandle: THandle;

implementation

uses SelCom,FbusMain, sTest, Licbox, UnitE1, UnitPrdSel, InputIniName, Ecodes, FlashBoots;
{$R *.dfm}
{$R myarr.res} 

function TForm1.AESEncrypt(SourceStream:TStream; DestStream:TStream; key:pointer): Boolean;
var
  DCP_rijndael1: TDCP_rijndael;
IV: array [0..15] of byte;
begin
  Result := True;
  FillChar(IV,16,0);
  try
    DCP_rijndael1 := TDCP_rijndael.Create(Self);
//    TDCP_blockcipher(DCP_rijndael1).CipherMode := cmCBC;
    DCP_rijndael1.Init(key^,16*8,@IV[0]);
//    DCP_rijndael1.InitStr(key, TDCP_sha1);
    DCP_rijndael1.EncryptStream(SourceStream, DestStream, SourceStream.Size);
    DCP_rijndael1.Burn;
    DCP_rijndael1.Free;
  except
    Result := False;
  end;
end;

function TForm1.AESDecrypt(SourceStream:TStream; DestStream:TStream; key:pointer;IV_in:pointer): Boolean;
var
  DCP_rijndael1: TDCP_rijndael;
IV: array [0..15] of byte;
begin
  Result := True;
  if IV_in=nil then FillChar(IV,16,0) else CopyMemory(@IV[0],IV_in,16);
  try
    DCP_rijndael1 := TDCP_rijndael.Create(Self);
//    TDCP_blockcipher(DCP_rijndael1).CipherMode := cmCBC;
    DCP_rijndael1.Init(key^,16*8,@IV[0]);
//    DCP_rijndael1.InitStr(key, TDCP_sha1);
    DCP_rijndael1.DecryptStream(SourceStream, DestStream, SourceStream.Size);
    DCP_rijndael1.Burn;
    DCP_rijndael1.Free;
  except
    Result := False;
  end;
end;

procedure TForm1.DeCriptB8(Buf:pointer);
var
 buffer_8_byte: string;
 i:integer;
 po:Pointer;
begin

  po:=Buf;
  buffer_8_byte := '';
  for i:=0 to 7 do begin buffer_8_byte:=buffer_8_byte+Chr(byte(Buf^)); Inc(integer(Buf)); end;
  {$I VM_Start.inc}
   buffer_8_byte:= dcp_3DESb8(key, buffer_8_byte, dcdDecrypt, dcmCBC);
    {$I VM_End.inc}
  for i:=1 to 8 do begin byte(po^):=Ord(buffer_8_byte[i]); Inc(integer(po)); end;
end;

procedure TForm1.ChPrdD();
begin
     case phsel of
     1: begin N0.Checked:=true;N1.Checked:=false;N2.Checked:=false;phoenixfolder:=prd1;end;
     2: begin N1.Checked:=true;N0.Checked:=false;N2.Checked:=false;phoenixfolder:=prd2;end;
     3: begin N2.Checked:=true;N1.Checked:=false;N0.Checked:=false;phoenixfolder:=prd3;end;
     end;
end;

procedure TForm1.FormCreate(Sender: TObject);   // Sozdanie formy
label term;
var
  F:TFileStream;
  fn:string;
  style:cardinal;
  s,sk,dat,dt:string;
  d:TDateTime;
  ds:TTimeStamp;
  i,j,Ln:integer;
  setini,flini:TIniFile;
  st:TResourceStream;
  tmnr : string;
begin

     Randomize;
     Rndmc;
//     Form2.Show;
     Application.ProcessMessages;
if not DirectoryExists('Phones_Data') then mkDir('Phones_Data');
if not DirectoryExists('Local_calc') then mkDir('Local_calc');
if not DirectoryExists('Backup') then mkDir('Backup');
if not DirectoryExists('Backup\Cert\') then mkDir('Backup\Cert\');
//if not DirectoryExists('Backup\flex_rpl\') then mkDir('Backup\flex_rpl\');
if not DirectoryExists('Logs') then mkDir('Logs');
if not DirectoryExists('Special') then mkDir('Special');
     if not FileExists('.\Special\special.log') then begin
               F:=TFileStream.Create('.\Special\special.log',fmCreate);
               F.Free;
     end;
DateTimeToString(tmnr,'DD_MM_YYYY_HH',now);
logfn:=GetCurrentDir+'\Logs\'+tmnr+'_log.txt';
      Application.ProcessMessages;
     FT_Enable_Error_Report:=false;
          TimOfClock.Enabled := false ;
          TimLic.Enabled := false ;
        TimConChk.Enabled:=false;
     if not connect then begin Application.Terminate; goto term; end;

  {$I VM_Start.inc}

     good:=true;
     stm:=0;
     MC:=TMemoryStream.Create;
     if FileExists('.\winscard.dll') then begin Application.Terminate; goto term; end;


     UserId:=GetUserId ;
     _msg('card found: '+ UserId);
     fullid:= GetFullId ;

     if BlackList(fullid) then  begin Application.Terminate; goto term; end;
     fn:= '.\license_best_'+fullid+'.dat';
     if not FileExists(fn) then begin
              _msg('License file not found :(');
              LicExists:=false ;
          TimLic.Enabled := true ;
          StatusBar.Panels.Items[6].Text :='BUZY';
              goto term ;
             end;
       F:=TFileStream.Create(fn,fmOpenRead);
       s:='';
       sk:='';
       SetLength(s,8);
       while F.Position<F.Size-1 do begin
       F.Read(s[1],8);
//       _msg(BufToHexStr(@s[1],8));

       sk:=sk+CardDeCrypt(s);
       end;
//       _msg(BufToHexStr(@sk[1],18));

       i:=1;
       s:='';
       Ln:=Ord(sk[i]);
       i:=i+1;
       for j:=1 to Ln do begin
       s:=s+sk[i];
       i:=i+1;
       end;
//       _msg(s);
       if s <> fullid then begin
           ShowMessage('License file is corrupt or invalid !');
           Application.Terminate;
           goto term;
       end;
       s:='';
       Ln:=Ord(sk[i]);
       i:=i+1;
       for j:=1 to Ln do begin
       s:=s+sk[i];
       i:=i+1;
       end;
       _msg('registered to: '+s);
       _msg('');
       UserId:=s+': '+UserId;
       s:='';
       Ln:=Ord(sk[i]);
       i:=i+1;
       for j:=1 to Ln do begin
       s:=s+sk[i];
       i:=i+1;
       end;
       crpass:=s;
//       _msg(BufToHexStr(@s[1],Length(s)));
       s:='';
       Ln:=Ord(sk[i]);
       i:=i+1;
       for j:=1 to Ln do begin
       s:=s+sk[i];
       i:=i+1;
       end;
       dat:=s;
       ds.Time:=0;
       ds.Date:=StrToInt(dat);
       if infinity then begin
       UidSrv:='00'+fullid;
       d:=TimeStampToDateTime(ds);
//       _msg(BufToHexStr(@s[1],Length(s)));
//       _msg('License expired: '+DateToStr(d));
//       _msg('');
//       Form1.Caption:= Form1.Caption+' special for Infinity users';
{       if CompareDate(d,Date)<0 then begin
           ShowMessage('License out of date!');
           Application.Terminate;
           goto term;
       end;
       end else begin
         if ds.Date=730120 then begin
         _msg('License expired: never');
         _msg('');
         end else begin
           ShowMessage('License out of date!');
           Application.Terminate;
           goto term;
         end;
 }      end else UidSrv:='03'+fullid;
//       _msg(UidSrv);

       s:='';
       Ln:=Ord(sk[i]);
       i:=i+1;
       for j:=1 to Ln do begin
       s:=s+sk[i];
       i:=i+1;
       end;
       key:=s;
//       _msg(BufToHexStr(@key[1],Length(key)));
       DeCriptB8(@ChkPhMode);
       DeCriptB8(@GETRoot);
       DeCriptB8(@APEtestrunsrv);
       DeCriptB8(@ReadS40cycle);
       DeCriptB8(@s60readcycle);
       DeCriptB8(@s40preformat);
       DeCriptB8(@GetS40PhbCouC);
       DeCriptB8(@GetS40PhbRecC);
       DeCriptB8(@S40PhbRecWr);
       DeCriptB8(@WriteData);

       DeCriptB8(@FbusArun);
       DeCriptB8(@fbuss60getdrv);
       DeCriptB8(@FChkPhMode);
       DeCriptB8(@FGetS40PhbCouC);
       DeCriptB8(@FGetS40PhbRecC);
       DeCriptB8(@FS40PhbRecWr);
       DeCriptB8(@FS40PhbRecWrEnd);
       DeCriptB8(@Flistdrv1);
       DeCriptB8(@schk);

       F.Free;
     st := TResourceStream.Create(HInstance, 'myarray', RT_RCDATA);
     DeCryptF(st,MC,key);
     st.Free;

    {$I VM_End.inc}
/// init lifetimer edits to digits only
    style := GetWindowLong(LTMEdt.Handle, GWL_STYLE);
    SetWindowLong(LTMedt.Handle, GWL_STYLE, style + ES_NUMBER);
    style := GetWindowLong(LTHEdt.Handle, GWL_STYLE);
    SetWindowLong(LTHedt.Handle, GWL_STYLE, style + ES_NUMBER);

StatusBar.Panels.Items[6].Text :='READY';
VplList:=TStringList.Create;
 setini:=TIniFile.Create(ExtractFileDir(Application.ExeName)+'\settings.ini');
     prd1:=setini.ReadString('prddir','1','');
     N0.Caption:=prd1;
     prd2:=setini.ReadString('prddir','2','');
     N1.Caption:=prd2;
     prd3:= setini.ReadString('prddir','3','');
     N2.Caption:=prd3;
     phsel:=setini.ReadInteger('prddir','ch',1);
     ChPrdD;
     pgc1.TabIndex:=setini.ReadInteger('core','TbSel',0);
     setini.ReadSection('Model',Modelsel.Items);
     Modelsel.ItemIndex:=0;
     setini.ReadSection('Download',suppar.Items);
     suppar.ItemIndex:=0;
    hndDLLHandle := loadLibrary ( 'BestSrvClient.dll' );
    if hndDLLHandle <> 0 then
    begin
      @SetServerIp := getProcAddress ( hndDLLHandle, 'fnSetServer' );
      @CallServer := getProcAddress ( hndDLLHandle, 'fnSL3ServerCall' );
//      @Ask2Rpl := getProcAddress ( hndDLLHandle, 'fnAskRplN' );
//      if addr ( SetServerIp ) <> nil then if addr ( CallServer ) <> nil then
//      if addr ( Ask2Rpl ) = nil then
//      _msg ( 'Function not exists...' );
    end
    else
      _msg ( 'DLL not found...' );

 StatusBar.Panels.Items[6].Text :='READY';
//StatusBar.Panels.Items[5].Text :='USB';
status:=False;
ConMode:=setini.ReadInteger('core','ConMod',0);
fbnum:=setini.ReadString('core','FbNum','1');
fbdev:=setini.ReadInteger('core','FbDev',0);
Application.ProcessMessages;
SelCoMode(ConMode);
Application.ProcessMessages;
StartDir:=GetCurrentDir+'\';
Usini.Checked:=setini.ReadBool('core','UsIni',false);
FlMan.Checked:=setini.ReadBool('core','ManFl',true);
UidPas:=setini.ReadString('server','password',GetPass);
UidSrv:=setini.ReadString('server','login',UidSrv);
//       _msg(UidPas);
SrvEd.Text:= setini.ReadString('server','IP','db.infinity-best.com');
  ///
  setini.free;
TimOfClock.Enabled:=True;
TimConChk.Enabled:=True;
stop:=False;
  ///
term:
//DisconnectFill;
end;

procedure TForm1.SelCoMode(mode:integer);
var
c_buf:string;
i:integer;
begin
    case mode of
    0:begin
      USB1.Checked:=true;
      COM1.Checked:=false;
      StatusBar.Panels.Items[5].Text :='USB';
      CloseCom;
      Close_USB_Device;
      chkDEADMODE.enabled:=True;
      chkDEADMODE.Checked:=false;
      end;
    1:begin
     if chkdeadmode.checked=true then
     begin
     chkDEADMODE.Checked:=false;
     Form1.StatusBar.Panels.Items[6].Text :='READY';
     SetReady;
     end;
        if fbdev=0 then begin
          port:=strtoint(fbnum);
          iComNum := port;
           if OpenCom(false) = true then begin
            _msg ( 'port COM'+IntToStr(iComNum) +' open OK ' ) ;
             PurgeCom(PURGE_TXCLEAR or PURGE_RXCLEAR);
             USB1.Checked:=false;
             COM1.Checked:=true;
             fbdev:=0;
             StatusBar.Panels.Items[5].Text :='COM'+IntToStr(iComNum);
             USBClosePort;
             Close_USB_Device;
           end else begin
           _msg ( 'port COM'+ IntToStr(iComNum) +' open error...' );
           USB1.Checked:=true;
           COM1.Checked:=false;
           StatusBar.Panels.Items[5].Text :='USB';
           CloseCom;
           Close_USB_Device;
           ConMode:=0;
           end;
        end else begin
          USBClosePort;
          if (ufx_boot(fbnum)) then
          begin
             if ufx_sw_fbus(fbnum,'FBUS') then _msg ( 'UFS S/N '+fbnum+' boot - Ok' );
             Application.ProcessMessages;
             USB1.Checked:=false;
             COM1.Checked:=true;
             StatusBar.Panels.Items[5].Text :=fbnum;
             ConMode:=1;
             fbdev:=1;
             //CloseCom;
             _msg('');
             chkDEADMODE.enabled:=false;
          end else begin
           _msg ( 'UFS S/N '+fbnum+' boot error...' );
           USB1.Checked:=true;
           COM1.Checked:=false;
           StatusBar.Panels.Items[5].Text :='USB';
           CloseCom;
           Close_USB_Device;
           ConMode:=0;
           end;
        end;
    end;
    end;
    cbbModeFlash.ItemIndex:=0;
DisconnectFill;
end;

procedure TForm1.clearlog1Click(Sender: TObject);
begin
lst1.Items.Clear;
end;
procedure TForm1.Copyinfo1Click(Sender: TObject);
begin
 clipboard.astext:=lst1.Items.Text;
end;

procedure TForm1.Copyselected1Click(Sender: TObject);
begin
  ListBoxToClipboard(1048000);
end;


//ListBox message procedure=========
function AddLog(LogStr:string):string;
var
  F: TFileStream;
  PStr: PChar;
  LengthLogString: integer;
begin
  LengthLogString := Length(LogStr) + 2;
  LogStr := LogStr + #13#10;
PStr := StrAlloc(LengthLogString + 1);
  StrPCopy(PStr, LogStr);
  if FileExists(logfn) then
    F := TFileStream.Create(logfn, fmOpenWrite)
  else
  F := TFileStream.Create(logfn, fmCreate);
  F.Position := F.Size;
  F.Write(PStr^, Length(LogStr));
  StrDispose(PStr);
  F.Free;
end;


procedure TForm1._msg(s:String);
begin
lst1.items.add(S);
Lst1.Perform(LB_SETTOPINDEX, Pred(Lst1.Items.Count), 0);
 try
 AddLog(s);
 except
 Application.ProcessMessages;
 end;
end;

procedure tform1.ListBoxToClipboard(buffersize:integer);
var
  Buffer: PChar;
  Size: Integer;
  Ptr: PChar;
  I: Integer;
  Line: string;
  Count: Integer;
begin
  GetMem(Buffer, BufferSize);
  Ptr   := Buffer;
  Count := 0;
  for I := 0 to Lst1.Items.Count - 1 do
  begin
    Line := Lst1.Items.strings[I];
    if not  Lst1.Selected[I] then
      Continue;
    { проверяем буффер на переполенние }
    Count := Count + Length(Line) + 3;
    if Count = BufferSize then
      Break;
    { впихиваем в буффер }
    Move(Line[1], Ptr^, Length(Line));
    Ptr    := Ptr + Length(Line);
    Ptr[0] := #13;
    Ptr[1] := #10;
    Ptr    := Ptr + 2;
  end;
  Ptr[0] := #0;
  ClipBoard.SetTextBuf(Buffer);
  FreeMem(Buffer, BufferSize);
end;

procedure tform1.SltestToClipboard(buffersize:integer);
var
  Buffer: PChar;
  Size: Integer;
  Ptr: PChar;
  I: Integer;
  Line: string;
  Count: Integer;
begin
  GetMem(Buffer, BufferSize);
  Ptr   := Buffer;
  Count := 0;
  for I := sltststart to sltstsend - 1 do
  begin
    Line := Lst1.Items.strings[I];
    { проверяем буффер на переполенние }
    Count := Count + Length(Line) + 3;
    if Count = BufferSize then
      Break;
    { впихиваем в буффер }
    Move(Line[1], Ptr^, Length(Line));
    Ptr    := Ptr + Length(Line);
    Ptr[0] := #13;
    Ptr[1] := #10;
    Ptr    := Ptr + 2;
  end;
  Ptr[0] := #0;
  ClipBoard.SetTextBuf(Buffer);
  FreeMem(Buffer, BufferSize);
end;
// List Box message end==============

//////////////////////////
///API premodule

procedure Tform1.disableFLtab;
begin
Form1.Modelsel.enabled:=False;
Form1.UsIni.Enabled:=False;
Form1.cbbSelPC.Enabled:=false;
Form1.FlMan.Enabled:=False;
Form1.chkDEADMODE.Enabled:=false;
Form1.UserIn.Enabled:=false;
Form1.btnSvUsIni.Enabled:=false;
end;

procedure Tform1.enableFLtab;
begin
Form1.Modelsel.enabled:=true;
Form1.UsIni.Enabled:=true;
Form1.cbbSelPC.Enabled:=true;
Form1.FlMan.Enabled:=true;
Form1.chkDEADMODE.Enabled:=True;
Form1.UserIn.Enabled:=true;
Form1.btnSvUsIni.Enabled:=true;
end;

procedure TForm1.BtnDisable();  //тута вырубаем все кнопки
begin
     InfoRdBtn.Enabled:=false;
     checkbtn.Enabled:=false;
     GetUcodebtn.Enabled:=False;
     ResetUCodebtn.Enabled:=False;
     ReadPrCodebtn.Enabled:=false;
     WritePrdbtn.Enabled:=false;
     ReadASKbtn.Enabled:=False;
     SetModeBtn.Enabled:=false;
     ReadPmBtn.Enabled:=false;
     ReadPPBtn.Enabled:=false;
     WritePPBtn.Enabled:=false;
     WritePmBtn.Enabled:=false;
     ReadLTbtn.Enabled:=False;
     ResetLTbtn.Enabled:=False;
     WriteLTbtn.Enabled:=false;
     DoFSetbtn.Enabled:=False;
     ExtPhbBtn.Enabled:=false;
     Calendarbtn.Enabled:=False;
     SDpassbtn.Enabled:=False;
     SaUsAr.Enabled:=false;
     RdSms.Enabled:=False;
     WritePBbtn.Enabled:=False;
     btnWriteCalendar.Enabled:=False;
     DoFormatbtn.Enabled:=False;
     btnNCKenter.Enabled:=False;
     btnInit.Enabled:=False;
       SetPatternBtn.Enabled:=false;
       btnADCread.Enabled:=False;
       btnSx4UplTune.Enabled:=false;
       btnWriteRPL.enabled:=false;
       btnFLASH.Enabled:=false;
       btnKeyBTest.Enabled:=False;
       btnFunLabel.Enabled:=False;
       chkDOWNGRADE.Enabled:=False;
       btnReadRPL.Enabled:=false;
       btnCamCheck.Enabled:=false;
       btnFormatS40LowLevel.Enabled:=False;
       btnReadCamConf.Enabled:=false;
        UplJ.Enabled:=true;
       CbLnck.Enabled:=false;
//       CbLnck.Checked:=false;
       RdUniKey.Enabled:=false;
       RSDD.Enabled:=false;
       btnWriteMsg.enabled:=False;
       chkPackread.enabled:=False;
//        ChUnl.Enabled:=false;
//        CncJ.Enabled:=false;
        SLxU.Enabled:=false;
          RepSLb.Enabled:=false;
         LsxB.Enabled:=false;
       //btnRdMess.Enabled:=false;
       //btnWriteMessg.Enabled:=false;
      if (ConMode=1) and (fbdev=1) and (operation=false) then
      begin
      checkbtn.enabled:=True;
      btnReadRPL.enabled:=True;
      btnWriteRPL.Enabled:=True;
      btnFLASH.Enabled:=true;
      btnFormatS40LowLevel.Enabled:=True;
      end;
end;

procedure TForm1.BtnEnable();
begin
     ChUnl.Enabled:=true;
     if ConMode=1 then begin
         if (fbdev=1) and (generation<>'40')
          and (generation<>'')
         then
         begin
          SLxU.Enabled:=true;
          UplJ.Enabled:=true;
          CbLnck.Enabled:=true;
          LsxB.Enabled:=true;
          RepSLb.Enabled:=true;
          RdUniKey.Enabled:=true;
          RSDD.Enabled:=true;
          end;
       if Generation <>'' then
      begin
       case strtoint(generation) of
       40:
        begin
        ExtPhbBtn.Enabled:=True;
        WritePBbtn.Enabled:=true;
        exit;
        end;
       30:
        begin
        //SaUsAr.Enabled:=True;
        //RdSms.Enabled:=True;
        //btnFunLabel.Enabled:=True;
        btnInit.Enabled:=True;
        btnADCread.Enabled:=True;
        WritePmBtn.Enabled:=True;
        ReadPmBtn.Enabled:=True;
        ReadPPBtn.Enabled:=True;
        ResetUcodebtn.Enabled:=True;
        WritePPBtn.Enabled:=True;
        ReadPrCodebtn.Enabled:=True;
        WritePrdbtn.Enabled:=True;
        DoFSetbtn.Enabled:=True;
        Exit;
        end;
        10,11,01,00 : Application.ProcessMessages;
       else
        begin
         if readset('stuff','WD2Force')=true then
         begin
         Form1._msg('Force WD2 enabled!!! Selecting WD2 mode');
         Form1._msg('');
         ExtPhbBtn.Enabled:=True;
         WritePBbtn.Enabled:=true;
         generation:='40';
         smart:=True;
         exit;
         end;
         SaUsAr.Enabled:=True;
         RdSms.Enabled:=True;
         btnFunLabel.Enabled:=True;
         btnInit.Enabled:=True;
         btnADCread.Enabled:=True;
         WritePmBtn.Enabled:=True;
         ReadPmBtn.Enabled:=True;
         ReadPPBtn.Enabled:=True;
         ResetUcodebtn.Enabled:=True;
         WritePPBtn.Enabled:=True;
         ReadPrCodebtn.Enabled:=True;
         WritePrdbtn.Enabled:=True;
         DoFSetbtn.Enabled:=True;
         Exit;
        end;
       end;
      end
      else
      begin
        if readset('stuff','WD2Force')=true then
        begin
        Form1._msg('Force WD2 enabled!!! Selecting WD2 mode');
        Form1._msg('');
        ExtPhbBtn.Enabled:=True;
        WritePBbtn.Enabled:=true;
        generation:='40';
        smart:=True;
        exit;
        end;
        SaUsAr.Enabled:=True;
        RdSms.Enabled:=True;
        btnFunLabel.Enabled:=True;
        btnInit.Enabled:=True;
        btnADCread.Enabled:=True;
        WritePmBtn.Enabled:=True;
        ReadPmBtn.Enabled:=True;
        ReadPPBtn.Enabled:=True;
        ResetUcodebtn.Enabled:=True;
        WritePPBtn.Enabled:=True;
        ReadPrCodebtn.Enabled:=True;
        WritePrdbtn.Enabled:=True;
        DoFSetbtn.Enabled:=True;
        Exit;
      end;
     end;

     chkDOWNGRADE.Enabled:=False;
     chkBackup.Enabled:=true;
     btnFLASH.Enabled:=True;
     InfoRdBtn.Enabled:=true;
     checkbtn.Enabled:=True;
     GetUcodebtn.Enabled:=true;

     if (Crypted='00') or (Crypted='10') then
     ResetUCodebtn.Enabled:=true
     else ResetUCodebtn.Enabled:=false;

    { if Generation='00' then
     begin
     grpPacketManager.Visible:=True;
     btnRdMess.Visible:=True;
     btnRdMess.Enabled:=True;
     btnWriteMessg.Enabled:=True;
     btnWriteMessg.Visible:=True;
     end
     else
     begin
     grpPacketManager.Visible:=False;
     btnRdMess.Visible:=False;
     btnRdMess.Enabled:=False;
     btnWriteMessg.Enabled:=False;
     btnWriteMessg.Visible:=False;
     end; }

     btnReadCamConf.Enabled:=true;
     ReadPrCodebtn.Enabled:=true;
     WritePrdbtn.Enabled:=true;
     ReadASKbtn.Enabled:=True;
     SetModeBtn.Enabled:=true;
     ReadPmBtn.Enabled:=true;
     WritePmBtn.Enabled:=true;
     ReadPPBtn.Enabled:=true ;
     WritePPBtn.Enabled:=true ;
     btnNCKenter.Enabled:=true;
     ReadLTbtn.Enabled:=true;
     ResetLTbtn.Enabled:=true;
     WriteLTbtn.Enabled:=true;
     DoFSetbtn.Enabled:=True;
     btnWriteRPL.Enabled:=true;
     DoFormatbtn.Enabled:=true;
     chkDOWNGRADE.Enabled:=True;
     if Generation<>'11'
     then
     begin
     ExtPhbBtn.Enabled:=true;
     Calendarbtn.Enabled:=true;
     SDpassbtn.Enabled:=true;
     RdSms.Enabled:=true;
     WritePBbtn.Enabled:=true;
     SaUsAr.Enabled:=true;
     btnWriteCalendar.Enabled:=True;
     end
     else
     begin
     ExtPhbBtn.Enabled:=true;
     Calendarbtn.Enabled:=true;
     SDpassbtn.Enabled:=true;
     WritePBbtn.Enabled:=true;
     SaUsAr.Enabled:=true;
     btnWriteCalendar.Enabled:=False;
     end;
     btnInit.Enabled:=True;
     btnSx4UplTune.Enabled:=True;
     btnCamCheck.Enabled:=true;
     btnKeyBTest.Enabled:=True;
     SetPatternBtn.Enabled:=true;
     btnADCread.Enabled:=True;
     btnFunLabel.Enabled:=False;

     if ConMode=1 then
     begin
       if Generation<>'11' then
       begin
       WritePBbtn.Enabled:=true;
       btnWriteCalendar.Enabled:=true;
       end
       else
       begin
       WritePBbtn.Enabled:=false;
       btnWriteCalendar.Enabled:=false;
       end;
      if fbdev=1 then btnFLASH.Enabled:=true else
      btnFLASH.Enabled:=false;
      btnCamCheck.Enabled:=false;
      btnReadCamConf.Enabled:=False;
     end;
     if generation='00' then
     begin
     btnFunLabel.Enabled:=True;
     if ConMode=0 then btnWriteMsg.Enabled:=True;
     if ConMode=0 then chkPackread.enabled:=True;
     end;
     if ConMode=0 then btnReadRPL.Enabled:=True;
     if generation='30' then
     begin
     CbLnck.Enabled:=false;
     CbLnck.Checked:=true;
     btnNCKenter.Enabled:=true;
     end;
     if StatusBar.Panels.Items[3].Text ='Disconnected' then begin
         UplJ.Enabled:=true;
       CbLnck.Enabled:=false;
       CbLnck.Checked:=false;
         exit;
         end else begin
     if CheckKeyExists(PhInfoRecord.IMEIPlain) then begin
         SLxU.Enabled:=true;
         UplJ.Enabled:=true;
       CbLnck.Enabled:=true;
         LsxB.Enabled:=true;
         RSDD.Enabled:=true;
          RepSLb.Enabled:=true;
         end else UplJ.Enabled:=false;
     end;
end;

procedure TForm1.DisconnectFill();  //тута вырубаем все кнопки
begin
  try
     PhInfoClear;
     BtnDisable;
     if ConMode=0 then USBclosePort;
     PrdEdit.Text:='';
     StatusBar.Panels.Items[0].Text :='';
     StatusBar.Panels.Items[1].Text :='';
     StatusBar.Panels.Items[2].Text :='';
     StatusBar.Panels.Items[4].Text :='';
     StatusBar.Panels.Items[3].Text :='Disconnected';
     RM:='';
    tphpach:=StartDir+'Phones_Data\';
     Smart:=False;
     TimOfClock.Enabled:=True;
     TimConChk.Enabled:=True;
     PhonePresentmode:=$00;
     _msg('Connect phone on selected interface...');
     _msg('');
     finally
     Application.ProcessMessages;
     end;
end;

procedure TForm1.ConnectFill();  //тута врубаем все кнопки
begin
     checkini;
     StatusBar.Panels.Items[3].Text :='Connected';
     BtnEnable;
     PhonePresentmode:=$01;
     PrdEdit.Text:= PhInfoRecord.ProductCode;
     StatusBar.Panels.Items[0].Text :=PhInfoRecord.PhType+' '+PhInfoRecord.Name;
     StatusBar.Panels.Items[1].Text :='MCU '+Copy(PhInfoRecord.MCUSW,1,7)+'; APE  '+PhInfoRecord.APECoreSW;
     StatusBar.Panels.Items[2].Text :=PhInfoRecord.IMEIPlain;
     StatusBar.Panels.Items[4].Text :=ReadPhMode;
     {if length(phinforecord.IMEIPlain)<>15 then
     begin
     BtnDisable;
      //busreset;
     DisconnectFill;
     SetReady;
     exit;
     end;  }
      PHName:=RightFileName(StatusBar.Panels.Items[0].Text+'_'+StatusBar.Panels.Items[2].Text);
    try
    if not DirectoryExists(RightFileName(StartDir+'Phones_Data\'+StatusBar.Panels.Items[2].Text)) then mkDir(RightFileName(StartDir+'Phones_Data\'+StatusBar.Panels.Items[2].Text));
    tphpach:=StartDir+'Phones_Data\'+RightFileName(StatusBar.Panels.Items[2].Text)+'\';
    except
    begin
     BtnDisable;
     if (conmode=1) and (fbdev=1) then
     begin
     busreset;
     Set_USB_Device_TimeOuts($2710,$2710);
     Application.ProcessMessages;
     end;
     DisconnectFill;
     SetReady;
     exit;
     end;
    end;

     if not FlMan.Checked then if Usini.Checked then begin
      Modelsel.Text:=RM;
      Usini.Checked:=false;
      Usini.Checked:=true;
//      FlMan.Checked:=false;
     end;
     if (Generation='') or (Generation='30') or (Generation='40') then StatusBar.Panels.Items[0].Text :=RM;
    cltrycn.ShowBalloonHint('Phone connected','Connected to : '+PhInfoRecord.Name,bitinfo,10);
end;

procedure TForm1.SetBuzy;  //тута вырубаем все кнопки
begin
     opstart:=GetTickCount;
     BtnDisable;
     operation:=True;
     StatusBar.Panels.Items[6].Text :='BUSY';
     cltrycn.Hint:='BEST v1.13 : Working now';
     Application.ProcessMessages;
end;

function TForm1.SetReady:string;  //тута врубаем все кнопки
begin
     BtnEnable;
     operation:=False;
     StatusBar.Panels.Items[6].Text :='READY';
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     cltrycn.ShowBalloonHint('BEST','Operation done!',bitinfo,10);
     cltrycn.Hint:='BEST v1.13 : Ready';
     Application.ProcessMessages;
     opend:=GetTickCount;
     Result:='Elapsed: '+showtime(opend-opstart);
     if (ConMode=1) and (fbdev=1) then EnUfsbutton;
     stop:=False;
     if btnFLASH.caption<>'FLASH' then btnFLASH.caption:='FLASH';
     if SaUsAr.caption<>'Save Gallery' then SaUsAr.caption:='Save Gallery';
     if RdSms.caption<>'Read SMS/MMS' then RdSms.caption:='Read SMS/MMS';
     form1.pb1.MaxValue:=100;
     Form1.pb1.Progress:=0;
     Form1.pb1.ForeColor:=clnavy;
     Application.ProcessMessages;
     enableFLtab;
end;

procedure TForm1.TimConChkTimer(Sender: TObject);
var
MMouse   : TMouse;
tp,tm    : word;
s,ss     : string;
i        : integer;
begin
  TypePHstr:='';
    if StatusBar.Panels.Items[6].Text ='READY' then begin
    TimConChk.Enabled:=false;
     StatusBar.Panels.Items[6].Text :='BUSY';
     Application.ProcessMessages;
     if stm=0 then begin
  {$I VM_Start.inc}
     tm:=MMouse.CursorPos.X and $00FF;
     tm:=tm shl 8;
     tp:=tm+(MMouse.CursorPos.y and $00FF);
     tp:=Rndc(tp);
     s:='';
     SetLength(s,8);
     word((@s[1])^):=tp;
     tm:=tp xor $1AC3;
     word((@s[3])^):=tm;
     tm:=tp xor $D2E7;
     word((@s[5])^):=tm;
     tm:=tp xor $A5C1;
     word((@s[7])^):=tm;
     ss:=CardCrypt(s);
//     _msg(BufToHexStr(@ss[1],8));
     MC.Seek((tp shl 3),soFromBeginning);
     MC.Read(s[1],8);
//     _msg(BufToHexStr(@s[1],8));
     if CompareStr(s,ss)<>0 then good:=false else good:=true;
     stm:=5;
  {$I VM_End.inc}
     end else stm:=stm-1;
      if StatusBar.Panels.Items[3].Text ='Disconnected' then begin
       BtnDisable;
       if StatusBar.Panels.Items[5].Text ='USB' then begin
        chkDEADMODE.Enabled:=True;
        if catchdevice=$01 then
        begin
        _msg('Phone found!');
        ReadPhoneInfo;
        RM:=s40pref;
        checkini;
        Smart:=false;
        if Generation<>'00' then Smart:=true;


        if Smart then {begin} _msg('Series 60 Device detected!')  //edtExtrFilePath.Text:='C:\private\100012a5\DBS_100065FF_Contacts.cdb'
         {end} else _msg('Series 40 Device detected!');
        _msg('read info...  - Ok');
        _msg('');
        ConnectFill;
        end;
       end else begin
        if PhOnComPresent then
        begin
          Application.ProcessMessages;
          Sleep(1000);
          Application.ProcessMessages;
          ReadPhoneInfo;
        RM:=s40pref;
         if (RM='') or (RM='Error') then
         begin
          if (PhInfoRecord.MCUSW='') or (PhInfoRecord.MCUSW='Error') then
          begin
             for i:=0 to 2 do
             begin
             Application.ProcessMessages;
             Sleep(1000);
             Application.ProcessMessages;
             end;
              ReadPhoneInfo;
              if (PhInfoRecord.MCUSW='') or (PhInfoRecord.MCUSW='Error') then
              begin
              i:=0;
              repeat
              Application.ProcessMessages;
              Sleep(500);
              Application.ProcessMessages;
              Sleep(500);
              Application.ProcessMessages;
              ReadPhoneInfo;
              inc(i);
              form1.statusbar.panels[0].text:='Wait phone '+inttostr(10-i);
              until  (i=10) or (PhInfoRecord.MCUSW<>'') and (PhInfoRecord.MCUSW<>'Error');
             end;
          end;
         end;
        if RM='' then rm:=getmodel(PhInfoRecord.MCUSW);
        TypePHstr:=checkini;
        Smart:=false;
        _msg('Phone found!');
        if (Generation<>'00') and (Generation<>'30') and (Generation<>'') then Smart:=true;


        if Smart then {begin} _msg('Series 60 Device detected!')  //edtExtrFilePath.Text:='C:\private\100012a5\DBS_100065FF_Contacts.cdb'
         {end} else _msg('Series 40 Device detected!');
        _msg('read info...  - Ok');
        _msg('');

        ConnectFill;
        end
        else
        begin
         if fbdev=1 then
         begin
          if UFsretry=10 then begin
           //reset voltage
           if (ufx_boot(fbnum)) then
           begin
             ufx_sw_fbus(fbnum,'FBUS');
             Application.ProcessMessages;
           end;
           UFSretry:=0;
          end
          else inc(UFsretry);
         end;

        end;
       end;
      end
      else
        begin
        if ConMode=1 then FbusSendSynk;
        StatusBar.Panels.Items[4].Text :=ReadPhMode;
        if ConMode=1 then
        begin
         if StatusBar.Panels.Items[4].Text='Error' then
         begin
          FbusSendSynk;
          StatusBar.Panels.Items[4].Text :=ReadPhMode;
         end;
        end;
        if StatusBar.Panels.Items[4].Text ='Error' then begin
         _msg('Phone disconected!');
         _msg('');
         if StatusBar.Panels.Items[5].Text ='USB' then USBClosePort;
        DisconnectFill;
        end;
       end;
  end
  else exit;
    TimConChk.Enabled:=true;
     StatusBar.Panels.Items[6].Text :='READY';
      if StatusBar.Panels.Items[3].Text ='Connected' then begin  chkDEADMODE.Enabled:=False; chkDEADMODE.checked:=False; end;
//     _msg (inttostr(conmode)+' '+inttostr(fbdev)+' '+fbnum);
     btnWriteRPL.Enabled:=True;
     btnReadRPL.Enabled:=True;
     btnFormatS40LowLevel.enabled:=True;
     Application.ProcessMessages;
end;

procedure TForm1.TimOfClockTimer(Sender: TObject);
begin
      Statusbar.Panels[7].Text:=TimeToStr(Time);
      if not good then begin Application.Terminate; exit; end;
end;

procedure TForm1.InfoRdBtnClick(Sender: TObject);
var
s,a:string;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
    a:='';
    SetBuzy;
     PhInfoClear;
    if not ReadPhoneInfoAll then _msg('Read phone info error :(') else begin
    Application.ProcessMessages;
    _msg('Reading Phone Info....');
    _msg('Connected phone -    '+PhInfoRecord.Name);
    _msg('Software ver : '+ChkBlankSt(PhInfoRecord.MCUSW));
    _msg('IMEI    :      '+PhInfoRecord.IMEIPlain);
    _msg('Ape Ver :      '+PhInfoRecord.APECoreSW);
    _msg('APE Var :      '+PhInfoRecord.APEVariant);
    _msg('APE ADSP:      '+PhInfoRecord.APEADSPSW);
    _msg('DSP Ver :      '+PhInfoRecord.DSP);
    _msg('APE Test:      '+PhInfoRecord.APETest);
    _msg('PPM     :      '+PhInfoRecord.PPMInfo);
    _msg('CNT     :      '+PhInfoRecord.CNT);
    _msg('Product SN   :     '+PhInfoRecord.PrdSerial);
    _msg('Product code :     '+PhInfoRecord.ProductCode);
    _msg('Base Prd.code:     '+PhInfoRecord.BisicPrdCode);
    _msg('Module code  :     '+PhInfoRecord.ModuleCode);
    _msg('Long Prod.SN :     '+PhInfoRecord.LSN);
    _msg('Hardware info=======');
    _msg('HWID  : '+ PhInfoRecord.HWID);
    _msg('Retu  : '+PhInfoRecord.Retu);
    _msg('Tahvo : '+PhInfoRecord.Tahvo);
    _msg('Batery: '+PhInfoRecord.Bat+' mV');
    _msg('Camera: '+PhInfoRecord.Cam);
    _msg('CMT BT: '+PhInfoRecord.CMTBtver);
    _msg('APE BT: '+PhInfoRecord.APEBT);
    _msg('APE HW: '+PhInfoRecord.APEHW);
    _msg('LCDVer: '+PhInfoRecord.LCD);
    _msg('RF ic : '+PhInfoRecord.Rfic);
    _msg('Lock info ===========');
    _msg('IMEI       : '+PhInfoRecord.IMEIPlain);
    _msg('IMEI spNet : '+PhInfoRecord.IMEI2Net);
    _msg('IMEI svNet : '+PhInfoRecord.IMEISv2Net);
    _msg('');
    
     try
     if conmode=0 then checklock(getlockfield)
     else checklock(getlockdata);
     except
     form1._msg('Error collect lock info, try again');
     end;
    //туттачки надоть делать построение сетки локов.....
       if ConMode=0 then begin
       if PhInfoRecord.IMEIPlain<>'12345610654321?' then begin
       _msg(CRT308backup);
       end else
       begin
       _msg('');
       _msg('IMEI data damaged, CRT save skipped... :('); end;
       _msg('');
       end;
           //
           a:=GetCodeUSB;
           if a<>'Error! Crypted user code!' then  _msg('User Code : '+a) else _msg('User code : Crypted');
           if Smart=false then begin  if savepwds40=True then _msg('MMC pwd  : Backup saved') else _msg('MMC pwd  : no any record found'); end;
           Application.ProcessMessages;
          if generation<>'' then begin
           case StrToIntdef(generation,22) of
            0:_msg('UserDataExLevel : Full [PhoneBook, Calendar, PWD, SMS, Gallery] ');
            1:_msg('UserDataExLevel : Full [PhoneBook, Calendar, PWD, SMS, Gallery] ');
           10:_msg('UserDataExLevel : Full [PhoneBook, Calendar, PWD, SMS, Gallery] ');
           11:_msg('UserDataExLevel : Low [Gallery] ')
           //22:_msg('Not found any info :( ');
           else _msg('UserDataExLevel : Error! Can'+#39+'t read initial data');
           end;
          end;
           Application.ProcessMessages;
           _msg('');
           //
    _msg('Done!');
    end;
    _msg('');
    SetReady;
end;

procedure TForm1.checkbtnClick(Sender: TObject);
var
  a,apestring,s     :string;
  b                 :Boolean;
  i                 :integer;
  cmtflash,apeflash :dword;
  xt                :integer;
  crps              :string;
begin
{$I VM_Start.inc}
    if not connect then begin Application.Terminate; exit; end;
    crps:=CardPass(crpass);
    if crps <> fullid then begin Application.Terminate; exit; end;
{$I VM_End.inc}

    SetBuzy;
    _msg('Read and Check phone data...');
    if ConMode=0 then begin
  if PhInfoRecord.IMEIPlain<>'12345610654321?' then
  begin
     cmtflash:=0;apeflash:=0;
    a:=check3stage;
   //_msg('Status ID : '+a);
   _msg('----------------------');
          //Check 2nd
          TransId:=$60; MsgBody:=$FF;
          check2nd[7]:=$16;
          check2nd[8]:=ISIHeaderTransId;
          check2nd[9]:=ISIHeaderMsgBody;
          USBBulkWritePort(@check2nd, Length(check2nd));
          USBBulkReadPort($FFFF);
          //GetRoot
          GetRoot[7]:=$16;
          GetRoot[8]:=ISIHeaderTransId;
          GetRAPInfo;

          b:=true;
          //РџСЂРѕРІРµСЂРєР° РЅР° РїСѓСЃС‚РѕР№ RootHash
          //for i := 0 to $0F do b:=b and (RAPInfo.Root_Key_Hash[i]<>0);
          if BufToHexStr(@RAPInfo.Root_Key_Hash[0],$0F)='00000000000000000000000000000000' then b:=False;
          if Not b then
          begin
               _msg('No RootKey Asic CMT. Damaged CRT/HW part...');
               a:='';
          end else begin
          _msg('RAP_BOOT:  '+ BufToHexStr(@RAPInfo.BootID[0],      Length(RAPInfo.BootID)));
          _msg('RAP_PUB:   '+ BufToHexStr(@RAPInfo.PublicID[0],    Length(RAPInfo.PublicID)));
          _msg('CMT_ROOT:  '+ BufToHexStr(@RAPInfo.Root_Key_Hash[0], Length(RAPInfo.Root_Key_Hash)));
          _msg('RAP_PAPUB: '+ BufToHexStr(@RAPInfo.PAPUBKEYSID[0], Length(RAPInfo.PAPUBKEYSID)));
          apestring:=BufToHexStr(@Rapinfo.APErootkey[0], Length(RAPInfo.APErootkey));
          if apestring<>'00000000000000000000000000000000' then
          _msg('APE_ROOT:  '+ apestring);
          _msg('----------------------');
          end;
          cmtflash:=dWord((@Rapinfo.FlashID[0])^);
          reversedword(@cmtflash);
          //cmtflash:=cmtflash Shl 2;
          //cmtflash:=cmtflash+Swap(Word((@Rapinfo.FlashID[6])^));
          apeflash:=dWord((@Rapinfo.APEFlashID[0])^);
          reversedword(@apeflash);
          //apeflash:=apeflash Shl 2;
          //apeflash:=apeflash+Swap(Word((@Rapinfo.APEFlashID[6])^));
   if a<>'' then _msg('Live Test Ok!') else _msg('Live test bad :(');
   _msg('----------------------');
   ReadFlashIc(cmtflash,apeflash);
   if not Smart then _msg('CNT sector : '+inttostr(getcntsize(cmtflash))+' kb');
  end
  else _msg('IMEI DAMAGED : Check impossible, Live status : BAD');
   _msg('------------------------');
   {_msg('Checking StartUp data : ');
   _msg('-----------------------'); }
   _msg('SDD Key status : '+checkSD);
       Application.ProcessMessages;
      sleep(50);
      a:='';
      a:=testitemst('21');
      if a='PASSED' then Form1._msg('SimLock status : SimLock is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('SimLock status : Can'+#39+'t get status ') else Form1._msg('SimLock status : SimLock Damaged!!!!! :('); end;
      Application.ProcessMessages;
      sleep(50);
      a:='';
      a:=testitemst('5D');
      if a='PASSED' then Form1._msg('Security status : Security is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('Security status : Can'+#39+'t get status ') else Form1._msg('Security status : Security Damaged!!!!! :(') end;
      a:='';
      _msg('');
       s:=PmReadRecord(120,2);
       if s<>'Error' then
       begin
        Form1._msg('PA_SimLock Version : ');
        if s='' then Form1._msg('PA_SL phone detected')
        else
        if Length(s)=40 then Form1._msg('PA_SL2 phone detected')
        else if Length(s)=260 then Form1._msg('PA_SL3 phone detected');
        _msg('');
       end;
   _msg('Done!');
   _msg('');
    s:='';
 end
 else
 begin
   case fbdev of
   0:begin
   _msg('Checking SD data now....');
   _msg('SDD Key status : '+checkSD);
       Application.ProcessMessages;
      sleep(50);
      a:='';
      a:=testitemst('21');
      if a='PASSED' then Form1._msg('SimLock status : SimLock is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('SimLock status : Can'+#39+'t get status ') else Form1._msg('SimLock status : SimLock Damaged!!!!! :('); end;
      Application.ProcessMessages;
      sleep(50);
      a:='';
      a:=testitemst('5D');
      if a='PASSED' then Form1._msg('Security status : Security is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('Security status : Can'+#39+'t get status ') else Form1._msg('Security status : Security Damaged!!!!! :(') end;
      a:='';
       _msg('');
       a:=checkSD;
       _msg('SDD Key status : '+a);
       s:=PmReadRecord(120,2);
       if s<>'Error' then
       begin
        Form1._msg('Checking PA_SimLock Version');
        if s='' then Form1._msg('PA_SL phone detected')
        else
        if Length(s)=40 then Form1._msg('PA_SL2 phone detected')
        else if Length(s)=260 then Form1._msg('PA_SL3 phone detected...');
       end;
   _msg('Done!');
   _msg('');
   end;
   1:begin
    DisUfsButton;
    case PhonePresentmode of
    $00:
     begin
       if core<>'' then
       if
       BB5ScanHeader(core)=$A
       then
       begin
       setbuzy;
        Form1._msg('Infineon checking...');
        SwitchBoxMode('FBUS');
        if not Boot_infineon then
        begin
         Form1._msg('Boot failed, phone not found');
         Form1._msg('');
         SetReady;
         exit;
        end;
         if not BusCheckInfineon then
         begin
         form1._msg('Error booting phone...');
         form1._msg('');
         SetReady;
         Exit;
         end;
         InfineonEnd;
       Application.ProcessMessages;
       _msg('');
       _msg('Done!');
       _msg('');
       SetReady;
       exit;
       end;
     BUsCheck;
     if boot_done=True then
     begin
     //if chkBackup.checked=true then grabrpl(1);
     UFSfinishsession;
     if apeexist then UFSEBLockAPE;
     UFSfinishsession;
     UFSeblock;
     if InitServiceMode
     then
     begin
      Application.ProcessMessages;
      sleep(50);
      a:='';
      xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('21');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

      if a='PASSED' then Form1._msg('SimLock status : SimLock is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('SimLock status : Can'+#39+'t get status ') else Form1._msg('SimLock status : SimLock Damaged!!!!! :('); end;
      Application.ProcessMessages;
      sleep(50);
      a:='';

      xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('5D');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

      if a='PASSED' then Form1._msg('Security status : Security is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('Security status : Can'+#39+'t get status ') else Form1._msg('Security status : Security Damaged!!!!! :(') end;
      a:='';
      Application.ProcessMessages;
      Fbussendsynk;
      if readset('stuff','extchk')=True then
      begin
        a:=checkSD;
        _msg('SDD Key status : '+a);
       _msg('');
       s:=PmReadRecord(120,2);
       if s<>'Error' then
       begin
        Form1._msg('PA_SimLock Version :');
        if s='' then Form1._msg('PA_SL phone detected')
        else
        if Length(s)=40 then Form1._msg('PA_SL2 phone detected')
        else if Length(s)=260 then Form1._msg('PA_SL3 phone detected');
        _msg('');
       end;
      end;
      Application.ProcessMessages;
      _msg('');
      _msg('Done!');
      _msg('');
      end
      else
      begin
      Form1._msg('Init Service Mode Failed, can'+#39+'t proceed checking... :(');
      Form1._msg('');
      end;
      end;
     end;
     $01:
     begin
       if Generation='30'
       then
       begin
        setbuzy;
        Form1._msg('Infineon checking...');
        Form1._msg('');
        Application.ProcessMessages;
            a:='';
            xt:=0;
            repeat
            Fbussendsynk;
            Sleep(100);
            Application.ProcessMessages;
            a:=testitemst('21');
            inc(xt);
            until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

            if a='PASSED' then Form1._msg('SIMLOCK TEST : Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('SIMLOCK TEST : Can'+#39+'t get status ') else Form1._msg('SIMLOCK TEST : Fail :('); end;
            Application.ProcessMessages;
            sleep(50);
            a:='';
            Application.ProcessMessages;
            a:='';
            xt:=0;
            repeat
            Fbussendsynk;
            Sleep(100);
            Application.ProcessMessages;
            a:=testitemst('2B');
            inc(xt);
            until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

            if a='PASSED' then Form1._msg('RUN TEST     : Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('RUN TEST     : Can'+#39+'t get status ') else Form1._msg('RUN TEST     : Fail :('); end;
            Application.ProcessMessages;
            sleep(50);
            a:='';
        Form1._msg('');
        SwitchBoxMode('FBUS');
        if not Boot_infineon then
        begin
         Form1._msg('Boot failed, phone not found');
         Form1._msg('');
         SetReady;
         exit;
        end;
         if not BusCheckInfineon then
         begin
         form1._msg('Error booting phone...');
         form1._msg('');
         SetReady;
         Exit;
         end;
         InfineonEnd;
        Application.ProcessMessages;
        _msg('');
        _msg('Done!');
        _msg('');
        DisconnectFill;
       SetReady;
       exit;
       end;
      Application.ProcessMessages;
      sleep(50);
      a:='';
      xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('21');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

      if a='PASSED' then Form1._msg('SimLock status : SimLock is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('SimLock status : Can'+#39+'t get status ') else Form1._msg('SimLock status : SimLock Damaged!!!!! :('); end;
      Application.ProcessMessages;
      sleep(50);
      a:='';

      xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('5D');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

      if a='PASSED' then Form1._msg('Security status : Security is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('Security status : Can'+#39+'t get status ') else Form1._msg('Security status : Security Damaged!!!!! :(') end;
      a:='';
      Application.ProcessMessages;
      Fbussendsynk;
       //_msg('');
      if readset('stuff','extchk')=True then
      begin
        a:=checkSD;
        _msg('SDD Key status : '+a);
       _msg('');
       s:=PmReadRecord(120,2);
       if s<>'Error' then
       begin
        Form1._msg('PA_SimLock Version : ');
        if s='' then Form1._msg('PA_SL phone detected')
        else
        if Length(s)=40 then Form1._msg('PA_SL2 phone detected')
        else if Length(s)=260 then Form1._msg('PA_SL3 phone detected');
        _msg('');
       end;
      end;
      Application.ProcessMessages;
      BUsCheck;
      if boot_done=True then
      begin
      //if chkBackup.checked=true then grabrpl(1);
      UFSfinishsession;
      if apeexist then UFSEBLockAPE;
      UFSfinishsession;
      UFSeblock;
      end;
      InitServiceMode;
     end;
    end;
    _msg('');
    Application.ProcessMessages;
    DisconnectFill;
    Sleep(200);
   end;
   end;
 end;
 SetReady;
end;



procedure TForm1.ResetUCodebtnClick(Sender: TObject);
var
  a,s  :string;
begin
{$I VM_Start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
{$I VM_End.inc}
    if ConMode<>0 then FbusSendSynk;
    SetBuzy;
    _msg('Resetting User Code to default (12345)...');
 
    if ConMode<>0 then FbusSendSynk;
    if Generation='30' then begin if InfineonResetCode then begin _msg('Code reset done, now it 12345 :)'); Form1._msg('Done'); form1._msg(''); SetReady; Exit; end else _msg('Code reset fail! :('); form1._msg(''); SetReady; Exit; end;
    if Generation=''   then begin if dct4codereset     then begin _msg('Code reset done, now it 12345 :)'); Form1._msg('Done'); form1._msg(''); SetReady; Exit; end else _msg('Code reset fail! :('); form1._msg(''); SetReady; Exit; end
    else begin
    if Generation='01' then begin
      //_msg('Old BB5 detected.. Using Old algo...');
      if Crypted<>'10' then OldBB5UReset else _msg('E-series : reset only startup code confirm');
     _msg(clearUCodedata(2));
      end
      else begin
        //_msg('Normal BB5 detected.. Using Normal algo');
      if Crypted<>'10' then UserCodeReset else _msg('E-series : reset only startup code confirm');
      _msg(clearUCodedata(1));
    end;
    if Crypted<>'10' then
    begin
    _msg('Result: '+GetCodeUSB);
    end;
    end;
    _msg('Done!');
    _msg('');
    SetReady;
end;

procedure TForm1.ReadPrCodebtnClick(Sender: TObject);
begin
    SetBuzy;
     _msg('Reading Product code...');
     PrdCodeRead;
     _msg('Product code : '+PhInfoRecord.ProductCode);
     PrdEdit.Text:=PhInfoRecord.ProductCode;
     _msg('Done!');
     _msg('');
    SetReady;
end;

procedure TForm1.WritePrdbtnClick(Sender: TObject);
var
  bf,cbf:string;
  i:Integer;
begin
   bf:=PrdEdit.Text; i:=1; cbf:=PrdEdit.Text;
   if Length(bf)<>7 then begin
   ShowMessage('Please, Enter 7-digit product code...');
   Exit;
   end
   else begin
    SetBuzy;
     _msg('Write Product code to phone...');

     if ConMode=0 then begin
        while i<8 do
     begin
          WriteProductCode[15+i]:=ord(bf[i]);
          inc(i);
     end;
     PrdCodewrite;
      _msg('Write done... Check now...');
     end
     else begin
      fbuswriteprdcode(PrdEdit.Text);
      _msg('Write done... Check now...');
     end;

      PrdCodeRead;
     _msg('Product code : '+PhInfoRecord.ProductCode);
     if PhInfoRecord.ProductCode=cbf then
     _msg('Code changed Ok!')
     else
     _msg('Error change... Need use another way...');
      _msg('');
    SetReady;
    end;
end;

procedure TForm1.ReadASKbtnClick(Sender: TObject);
var
  ASKfile: SYSTEM.Text;
  buf:string;
begin
    with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[2].Text ;
       InitialDir := '.\';
       DefaultExt := 'ask';
       Filter := 'ASK files (*.ask)|*.ask';
       Title:='Save ASK file to ...';
      end;
       if SaveDialog.Execute then begin
            SetBuzy;
             System.Assign (ASKfile , SaveDialog.FileName ) ;
             System.Rewrite ( ASKfile );
    _msg('Reading ASK request file...');
   buf:=GettingASK;
      System.WriteLn(ASKfile, '[CERT_PROG_DATA_IN]');
      System.WriteLn(ASKfile, 'RAP_PUBLIC_ID='+buf);
      System.Close ( ASKfile );
    _msg('Saved to: '+SaveDialog.FileName );
    _msg('Done!');
    _msg('');
    SetReady;
  end
  else SetReady;
end;


procedure TForm1.FullPMRadClick(Sender: TObject);
begin
         PmFromEd.Enabled:=false;
         PmToEd.Enabled:=false;
         PmFromEd.Text:=' 000';
         PmToEd.Text:=' 400';
end;

procedure TForm1.RangePMRadClick(Sender: TObject);
begin
         PmFromEd.Enabled:=true;
         PmToEd.Enabled:=true;
end;

procedure TForm1.SetModeBtnClick(Sender: TObject);
begin
    SetBuzy;
     if CBoxSetMode.Text<> StatusBar.Panels.Items[4].Text then begin
     _msg('Set phone in '+CBoxSetMode.Text+' mode...');
     _msg('Restarting...');
     Application.ProcessMessages;
     SetCheckPhModeStr(CBoxSetMode.Text);
        sleep(5000);
     Application.ProcessMessages;
     end else _msg('Phone already in '+CBoxSetMode.Text+' mode');
    _msg('Done!');
    _msg('');
    SetReady;
end;

procedure TForm1.ReadPmBtnClick(Sender: TObject);
var
PMFile:System.Text;
s:string;
start,stop:word;
Len:dword;
j,i,er,k:integer;
trys : Integer;
begin
      val(Copy(PmFromEd.Text,2,3),start,er);
      val(Copy(PmToEd.Text,2,3),stop,er);
     if start<=stop then begin

      with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[0].Text+'_'+StatusBar.Panels.Items[2].Text+'_'+inttostr(start)+'_'+ inttostr(stop) ;
       InitialDir := '.\Backup\';
       DefaultExt := 'pm';
       Filter := 'pm files (*.pm)|*.pm';
       Title:='Save PM file to ...';
      end;
    if SaveDialog.Execute then begin
      SetBuzy;
             System.Assign ( PMFile , SaveDialog.FileName ) ;
             System.Rewrite ( PMFile );
          if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
      // SetMode('Local');
       end;
       pb1.MaxValue:=stop;
       pb1.Progress:=0;
      _msg('Reading PM from field '+IntToStr(start)+' to '+IntToStr(stop));
      _msg('');
       Application.ProcessMessages;
      for i:=start to stop do begin
        trys:=0;
        er:=PmGetRecCou(i);
        //correection if error
        if er>2000 then
        repeat
         if ConMode=1 then FbusSendSynk;
         er:=PmGetRecCou(i);
         Application.ProcessMessages;
         Inc(trys);
        until (er<2000) or (trys=20);
        if trys=20 then er:=0;
        //correction if error
        if er<>0 then
        begin
        System.WriteLn (PmFile,'['+IntToStr(i)+']');
        _msg('Field ['+IntToStr(i)+']    '+IntToStr(er)+' Record(s)');
            k:=0;
          pbsm1.MaxValue:=er;
          while er<>0 do
          begin
             Len:=PmGetRecLen(i,k);
              if Len<$F0000000 then
              begin
              s:=PmReadRecordWithOutCheck(i,k,Len);
              System.WriteLn (PmFile,IntToStr(k)+'='+s);
              _msg('   Record '+IntToStr(k)+': '+IntToStr(Len)+ ' byte(s) readed - Ok');
              er:=er-1;
              pbsm1.Progress:= pbsm1.Progress+1;
              Application.ProcessMessages;
              end;
              k:=k+1;
          end;
          pbsm1.Progress:=0;
        end;
      pb1.Progress:=i;
      end;
      System.Close ( PMFile );
      _msg('');
      _msg('Saved as '+SaveDialog.FileName);
      _msg('Done!');
        Application.ProcessMessages;
      _msg('');
      _msg(SetReady);
      _msg('');
      end;

     end else _msg('Invalid range value!');
      pb1.Progress:=0;
end;


///by Lead 10.09.2009//////

procedure TForm1.ResetLTbtnClick(Sender: TObject);
var
  s:string;
begin
  {$I VM_Start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
  {$I VM_End.inc}
  SetBuzy;
    _msg('Resetting life Timer...');
     resetLTnew;
    _msg('Done');
    _msg('');
  SetReaDy;
end;



procedure TForm1.ReadLTbtnClick(Sender: TObject);
var
  a, ss : string;
  b, h, m, s, mo, mv, ms, sf:integer;
  bs : string;
  Last, received, all : Dword;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    a:=CardPass(crpass);
    if a <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  LTHedt.text:='';
  LTMedt.Text:='';
  _msg('Reading LifeTimer data...');
  b:=ReadLTF;

  if (b=0) or (b=4) then
  begin
   _msg('Looks like LifeTimer already reset...');
   _msg('');
   SetReady;
   Exit;
  end; 
 
  if ltdata<>0 then
  begin
  _msg('LifeTime is: '+inttostr(ltdata)+' seconds');
   sf:=ltdata;
   mo:=sf div 60;
   mv:=mo*60;
   s:=sf-mv;
   h:=mo div 60;
   ms:=h*60;
   m:=mo-ms;
  _msg('Phone works: '+inttostr(h)+' Hours; '+inttostr(m)+' minutes; '+inttostr(s)+' seconds');
  LTHedt.text:=IntToStr(h);
  LTMedt.Text:=IntToStr(m);
  end
  else _msg('Looks like LifeTimer already reset...');

   if b=2 then
   begin
    if ConMode=1 then FbusSendSynk;
    bs:=Pmreadrecord(373,0);
    if (bs<>'') and (bs<>'Error') then
    begin
     _msg('Last calls : ');
     Last:=hextoint(copy(bs,1,8));
     Dwordswap(@last);
     form1._msg('Last call : '+FormatDateTime('hh:nn:ss',(SecondToTime(last))));
     received:=hextoint(copy(bs,25,8));
     DwordSwap(@received);
     form1._msg('Total received calls : '+FormatDateTime('hh:nn:ss',(SecondToTime(received))));
     all:=hextoint(copy(bs,49,8));
     dwordswap(@all);
     form1._msg('Total sent calls : '+FormatDateTime('hh:nn:ss',(SecondToTime(all))));
    end;
   end;
  _msg('Done');
  _msg('');
  SetReady;
end;

procedure TForm1.GetUcodebtnClick(Sender: TObject);
var
  a:string;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    a:=CardPass(crpass);
    if a <> fullid then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Reading User code...');
  _msg('User Code is: '+GetCodeUSB);
  _msg('Done!');
  _msg('');
  SetReady;
end;


procedure TForm1.DoFSetbtnClick(Sender: TObject);
var
  s:string;
begin
if (FullFactorychk.Checked or Swupgrdefchk.Checked or ServiceCentrechk.Checked or
      PrdTunechk.Checked or UserDatachk.Checked or LeaveFactorychk.Checked) then begin

if (MessageBox(0, 'Are You sure want do factory settings?'+#13+#10+'When Full Factory or User Data checked - All not saved data will be deleted!'+#13+#10+'If You  want do Factory settings - press Yes...', 'Conformation before reset.... ', MB_ICONWARNING or MB_YESNO) = idYes) then
begin
   SetBuzy;
  _msg('Resetting selected items...');
    SetMode('Test');

  If FullFactorychk.Checked=true then begin
  _msg('Settings Full Factory Defaults...');
  If not FullFactorySet then begin
    _msg('Error When resetting Full factory :( ...');
    Application.ProcessMessages;
    end
     else
    _msg('Set OK!');
    end;

  if Swupgrdefchk.Checked=true then  begin
  _msg('Settings Software Upgrade Defaults...');
  If not SWupgrDef then begin
    _msg('Error When setting Software Upgrade Defaults :( ...');
    Application.ProcessMessages;
    end
    else
    _msg('Set OK!');
    end;

  if ServiceCentrechk.Checked=true then  begin
  _msg('Settings Service Centre Defaults...');
  If not ServiceCentreDef then begin
    _msg('Error When setting Service Centre defaults :( ...');
    Application.ProcessMessages;
    end
     else
    _msg('Set OK!');
    end;

  if PrdTunechk.Checked=true then   begin
  _msg('Settings Production Tune Defaults...');
  If not PrdTuneSet then begin
    _msg('Error When settinng Production Tune defaults :( ...');
     Application.ProcessMessages;
    end
     else
    _msg('Set OK!');
    end;

    if  UserDatachk.Checked=true then begin
      _msg('Settings User Data Defaults...');
    if not UserDefSet then begin
      _msg('Error When setting User Data defaults :( ... ');
     Application.ProcessMessages;
    end
     else
    _msg('Set OK!');
    end;

    if LeaveFactorychk.Checked=True then begin
      _msg('Settings Leave Factory defaults...');
      if not LeaveFactSet then begin
         _msg('Error When setting Leave Factory Defaults :( ...');
          Application.ProcessMessages;
    end
     else
    _msg('Set OK!');
    end;

    _msg('');
    _msg(SetReady);
    _msg('');
end
else Exit;
end else begin _msg('Nothing to set :( ... Skip operations'); _msg(''); end;
end;

procedure TForm1.prereadstuff();
var
  a:string;
begin
  if ScanProcess then begin Application.Terminate; exit; end;
       _msg('SmartPhone algo initialise...');
       _msg('Setup data...');
       _msg('StartUp FileSystem...');
end;

procedure TForm1.ExtPhbBtnClick(Sender: TObject);
var
s,s1,cn,tmps:string;
er,i,j:integer;
k:word;
Len,b:dword;
fl6700:integer;
F:TFileStream;
MM:TMemoryStream;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
    if not Smart then begin
     pb1.Progress:=0;
     if (datapos='11') or (datapos='21') or (datapos='31')then begin
     with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text) ;
       InitialDir := '.\';
       DefaultExt := '.S4pb';
       Filter := 'S40 OpenPhoneBook (*.S4pb)|*.S4pb';
       Title:='Save S40 OpenPhoneBook file to ...';
       end;
       if SaveDialog.Execute then begin
         SetBuzy;
         //SetMode('Local');
         _msg('BackUp UserData : [PhoneBook]');
         _msg('Generation mode : [S40]');
         if ScanProcess then begin Application.Terminate; exit; end;
         case conmode of
         0:GetPBstatus;
         1:Application.ProcessMessages;
         end;
         if datapos='11' then
         begin
           if readset('stuff','altway')=True then
           begin
           Form1._msg('= > Alternative mode selected');
           s:='C:/predefhiddenfolder/phonebook/persistentmemory/0001/LM_0005/LM_0005.pbr';
           end else
           s:='C:/predefhiddenfolder/phonebook/persistentmemory/0002/LM_0005/LM_0005.pbr';
           fl6700:=$ae4;
         end
         else
         begin
           if datapos='21' then
           begin
             if readset('stuff','altway')=True then
             begin
             Form1._msg('= > Alternative mode selected');
             s:='C:/predefhiddenfolder/phonebook/persistentmemory/0001/LM_0005.pbr';
             end else
           s:='C:/predefhiddenfolder/phonebook/persistentmemory/0002/LM_0005.pbr';
           fl6700:=$13a1;
           end
           else
           begin
             if readset('stuff','altway')=True then
             begin
             Form1._msg('= > Alternative mode selected');
             s:='C:/predefhiddenfolder/phonebook/persistentmemory/0001/LM_0005.pbr';
             end else
           s:='C:/predefhiddenfolder/phonebook/persistentmemory/0002/LM_0005.pbr';
           fl6700:=$EB9;
           end;
         end;

         // simply reading .pbr file
         //predefhiddenfolder\phonebook\persistentmemory\0002\LM_0005\LM_0005.pbr
         //predefhiddenfolder\phonebook\persistentmemory\0001\LM_0005\LM_0005.pbr
          b:=s40getsizeuni(s);
                  if b>0 then begin
                   //_msg('Found!');
                   s1:=tphpach+'VCF\';
                   CreateDir(s1);
                   cn:=ChangeFileExt(SaveDialog.FileName,'.csv');
                   M:=TMemoryStream.Create;
                   s40extractuni(M,s,b,1);
                   M.Seek(0,soFromBeginning);
                   j:=0;
                   if M.Size>0 then begin
                    MM:=TMemoryStream.Create;
                    word((@Buf[0])^):=0;
                    MM.Write(Buf[0],2);
                    Application.ProcessMessages;
                    Pb1.Progress:=0;
                    Pb1.MaxValue := M.Size ;
            if csvch.Checked then begin
             F:=TFileStream.Create(cn,fmCreate);
             tmps:=('Name ; Surname ; Common ; Home ; Mobile ; Fax ; Oth/Vid ; Work ; e-mail ; OffName ; Nick ; Address ; Post ; Company ; Birthday ; Note ; Group ; WWW ; UserId ; PTT ');
             F.Write(tmps[1],Length(tmps));
             word ((@Buf[0])^):=$0A0D;
             F.Write(Buf[0],2);
            end;
                     while M.Position<>M.Size do begin
                        M.Read (Buf[0],fl6700);
                        if word((@Buf[0])^)<>0 then begin
                        ClearRec();
                        NokiaTRCnv(@Buf[0]);
                        SaveVcf(s1,j);
            if csvch.Checked then begin
             tmps:=Utf8toAnsi(BookRecord.Name+';'+ BookRecord.SurName+';'+BookRecord.OsnTelNum+';'+
                     BookRecord.HomTelNum+';'+BookRecord.MobTelNum+';'+BookRecord.FaxTelNum+';'+
                     BookRecord.OthTelNum+';'+BookRecord.WorTelNum+';'+BookRecord.emale+';'+
                     BookRecord.OffName+';'+BookRecord.NickName+';'+AdrStr(' ')+';'+
                     BookRecord.Post+';'+BookRecord.Company+';'+BookRecord.Birthday+';'+
                     BookRecord.note+';'+BookRecord.idgroup+';'+BookRecord.http+';'+
                     BookRecord.userid+';'+BookRecord.ptt);
             F.Write(tmps[1],Length(tmps));
             word ((@Buf[0])^):=$0A0D;
             F.Write(Buf[0],2);
             end;
                        s:=ConvNokPhb;
                        i:=StrToBufHex(s,@Buf[0]);
                        MM.Write(Buf[0],i);
                        j:=j+1;
                        end;
                        Pb1.Progress:=M.Position;
                     end;
                     Pb1.Progress:=0;
                     MM.Seek(0,soFromBeginning);
                     word((@Buf[0])^):=j;
                     MM.Write(Buf[0],2);
                     MM.Seek(0,soFromBeginning);
//                    F.CopyFrom(M,M.Size);
            if csvch.Checked then begin
            F.Free;
            _msg('csv file save to '+cn);
            end;
                    if j=0 then begin
                    _msg('Phonebook clear... :(');
                    SetReady;
                    MM.Free;
                    M.Free;
                    _msg('');
                    Exit;
                    end;
                     _msg(IntToStr(j)+' phonebook records are found!');
                     F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
                     EncryptF(MM,F,fullid);
                     F.Free;
                    _msg('VCF Records saved to : BEST\Phones_Data\IMEI\');
                    _msg('File saved to : '+savedialog.FileName);
                    MM.Free;
                   end;
                   M.Free;
                   _msg('Read done ;)');
                  end
                else begin
                     _msg('Phonebook not found or clear... :(');
                      SetReady;
                     _msg('');
                      Exit;
                 end;

          _msg('Done...');
          _msg('');
          SetReady;
          Exit;

       end else
       begin
       SetReady; Exit;
       end;

     end
     else
     begin

      with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text) ;
       InitialDir := '.\';
       DefaultExt := '.S4pb';
       Filter := 'S40 OpenPhoneBook (*.S4pb)|*.S4pb';
       Title:='Save S40 OpenPhoneBook file to ...';
       end;
       if SaveDialog.Execute then begin
         SetBuzy;
//         SetMode('Local');
         _msg('BackUp UserData : [PhoneBook]');
         _msg('Generation mode : [S40]');
       if ScanProcess then begin Application.Terminate; exit; end;
       er:=PmGetRecCou(58);
//       _msg('PN : ['+IntToStr(er)+']');
//      er:=GetS40PhbCou;
        if er<>0 then begin
                   s1:=tphpach+'VCF\';
                   CreateDir(s1);
                   cn:=ChangeFileExt(SaveDialog.FileName,'.csv');
         M:=TMemoryStream.Create;
         word((@Buf[0])^):=0;
         M.Write(Buf[0],2);
         pb1.MaxValue:=er;
          _msg('Reading Phonebook...');
            k:=0;
            j:=0;
            if csvch.Checked then begin
             F:=TFileStream.Create(cn,fmCreate);
             tmps:=('Name ; Surname ; Common ; Home ; Mobile ; Fax ; Oth/Vid ; Work ; e-mail ; OffName ; Nick ; Address ; Post ; Company ; Birthday ; Note ; Group ; WWW ; UserId ; PTT ');
             F.Write(tmps[1],Length(tmps));
             word ((@Buf[0])^):=$0A0D;
             F.Write(Buf[0],2);
            end;
          while j<>er do begin
             Len:=PmGetRecLen(58,k);
              if Len<>$F0000000 then begin
             s:=PmReadRecordWithOutCheck(58,k,Len);
             S40PhbExtr(s);
             SaveVcf(s1,j);
            if csvch.Checked then begin
             tmps:=Utf8toAnsi(BookRecord.Name+';'+ BookRecord.SurName+';'+BookRecord.OsnTelNum+';'+
                     BookRecord.HomTelNum+';'+BookRecord.MobTelNum+';'+BookRecord.FaxTelNum+';'+
                     BookRecord.OthTelNum+';'+BookRecord.WorTelNum+';'+BookRecord.emale+';'+
                     BookRecord.OffName+';'+BookRecord.NickName+';'+AdrStr(' ')+';'+
                     BookRecord.Post+';'+BookRecord.Company+';'+BookRecord.Birthday+';'+
                     BookRecord.note+';'+BookRecord.idgroup+';'+BookRecord.http+';'+
                     BookRecord.userid+';'+BookRecord.ptt);
             F.Write(tmps[1],Length(tmps));
             word ((@Buf[0])^):=$0A0D;
             F.Write(Buf[0],2);
             end;
//             _msg(Utf8Decode(BookRecord.Name+' '+BookRecord.SurName+' '+BookRecord.OsnTelNum));
             s:=ConvNokPhb;
             Len:=StrToBufHex(s,@Buf);
             M.Write(Buf[0],Len);
//             _msg(BufToHexStr(@buf,Len));

             j:=j+1;
             pb1.Progress:=pb1.Progress+1;
             Application.ProcessMessages;
            end;
            k:=k+1;
          end;
          pb1.Progress:=0;
            if csvch.Checked then begin
            F.Free;
            _msg('csv file save to '+cn);
            end;
          _msg(IntToStr(j)+' phonebook records are found!');
          M.Seek(0,soFromBeginning);
          word((@Buf[0])^):=j;
          M.Write(Buf[0],2);
          M.Seek(0,soFromBeginning);
          if M.Size>2 then begin
          F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
//       F.CopyFrom(M,M.Size);
          EncryptF(M,F,fullid);
          F.Free;
         end;
         M.Free;
         _msg('VCF Records saved to : BEST\Phones_Data\IMEI\');
         _msg('Saved to: '+SaveDialog.FileName );
          pb1.Progress:=0;
          _msg('Done...');
          _msg('');
          SetReady;
          Exit;
        end else begin
         _msg('Phonebook not found or clear... :(');
          pb1.Progress:=0;
          _msg('');
          SetReady;
          Exit;
        end;

      end
      else SetReady;
     end;
    end
    else
    begin
      if (ConMode=1) and (Generation='40') then begin
        _msg('WD2 mode autoselected...');
        _msg('BackUp UserData : [PhoneBook]');
        _msg('Generation mode : S60 [WD2]');
        if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
        _msg('Operating mode is OK, no need change...');
         Application.ProcessMessages;
         end
        else begin
        SetMode('Test');
        end;
        WD2ExtractPhoneBook;
        _msg('');
        Exit;
      end;

      with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text) ;
       InitialDir := '.\';
       DefaultExt := '.Bs60pb';
       Filter := 'SmartPhopneBook (*.Bs60pb)|*.Bs60pb';
       Title:='Save SmartPhoneBook file to ...';
       end;
         if SaveDialog.Execute then begin
         SetBuzy;
         b:=0;
        _msg('BackUp UserData : [PhoneBook]');
        _msg('Generation mode : [S60]');
     if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else SetMode('Test');

    /// начнем, пожалуй ;)
      prereadstuff;
      Application.ProcessMessages;
     if not startFS60uni then
     begin
      _msg('FS run fail, please, remove SD card first');
      _msg('Change phone mode manualy to local/test and try again');
      _msg('If still no luck - phone have damaged FS/SD-MMC part..');
      Form1._msg('');
      SetReady;
      Exit;
     end
     else _msg('Fsrun OK...');

      _msg('Detect Symbian OS Generation...');
       M:=TMemoryStream.Create;
      if not USBS60SecReadData(M,StrToInt(generation),1) then begin
       _msg('Error during read...');
       _msg('');
       M.Free;
       SetReady;
       Exit;
       end
       else begin
                   s1:=tphpach+'VCF\';
                   CreateDir(s1);

     s:=ChangeFileExt(SaveDialog.FileName,'.csv');
     M.Seek(0,soFromBeginning);
       i:=SmartExtract(M,s1,s);
       if i<>0 then begin
       _msg(IntToStr(i)+' vcf files saved to '+s1);
       F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
       EncryptF(M,F,fullid);
       F.Free;
       _msg('File saved to : '+savedialog.FileName);
       end else _msg('Contacts not found... :(');
        M.Free;
       _msg('Read done ;)');
      end;
    pb1.Progress:=0;
    _msg('Done...');
    _msg('');
    SetReady;
    Exit;
    end
    else SetReady;
  end;

end;

procedure TForm1.WritePmBtnClick(Sender: TObject);
var
PMFile:System.Text;
s,sf,sr:string;
field,rec:word;
i:integer;
begin
 if (MessageBox(0, ' Warnig!'+#13+#10+' PM writing - if You don''t know, what You doing - can destroy phone permanently!', 'Think, before do..', MB_ICONWARNING or MB_OKCANCEL) in [idOk]) then begin
      with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\Backup\';
       DefaultExt := 'pm';
       Filter := 'pm files (*.pm)|*.pm';
       Title:='Open PM file ';
      end;
    if OpenDialog.Execute then begin
      setBuzy;
    System.Assign ( PMFile , OpenDialog.FileName ) ;
    System.Reset(PMFile);
     if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
     SetMode('Local');
     end;
    _msg('');
    pb1.MaxValue:=400;
    while not Eof (PMFile) do begin
      System.Readln(PMFile,s);
       if s<>'' then begin
        if s[1]='[' then begin
          sf:=''; i:=2;
          while s[i]<>']' do begin
          sf:=sf+s[i]; i:=i+1;
          end;
          field:=StrToInt(sf);
          pb1.Progress:=field;
          _msg('Field '+IntToStr(field));
        end else begin
         i:=1; sr:='';
         while s[i]<>'=' do begin
          sr:=sr+s[i]; i:=i+1;
         end;
         rec:=StrToInt(sr);
         s:=Copy(s,i+1,Length(s)-i+1);
//    _msg(PmWriteRecord(4,5,'3035343831313600'));
          _msg('   Record '+IntToStr(rec)+' write - '+PmWriteRecord(field,rec,s));

        end;
       end;
      end;
    System.Close(PMFile);
    pb1.Progress:=400;
    _msg('');
    _msg('Done!');
    _msg('');
    _msg(SetReady);
    _msg('');
    pb1.Progress:=0;
    end;
 end;
end;

procedure TForm1.SetMode(mode:string);
var
s:string;
begin
     _msg('Check phone mode...');
     s:=ReadPhMode;
     if s <>mode then begin
     _msg('Phone in '+s+' mode');
     _msg('Seting '+mode+' mode... wait...');
     Application.ProcessMessages;
     SetCheckPhModeStr(mode);
     _msg(mode+' mode set');
     Application.ProcessMessages;
     end else _msg('Phone already in '+mode+' mode, skip change...');
end;

procedure TForm1.WriteLTbtnClick(Sender: TObject);
var
  sum      :Integer;
  a,s      :string;
  ltframe  :DWORD;
  b        :integer;
begin
{$I VM_Start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
{$I VM_End.inc}

  if LTHedt.Text='' then begin
    if LTMedt.Text='' then begin
      _msg('Error! Choose need LifeTime value for write!');
      _msg('');
      Exit;
      end
  end;

  SetBuzy;

  _msg('Will write LifeTime data...');
  _msg('Set value: '+LTHedt.text+' h, '+LTMedt.Text+' m');

  if LTHedt.Text='' then LTHedt.Text:='000';
  if LTMedt.Text='' then LTMedt.Text:='000';

  sum:=StrToInt(LTHedt.text)*3600+StrToInt(LTMedt.Text)*60;
  _msg('Creating data block...');
  ltframe:=sum;
   b:=0;
   b:=ReadLTF;

  case b of
  1:
   begin
    _msg('Writing Block....');
    case ConMode of
     0:
     begin
     DWord((@WriteLTframe[52])^):=ltframe;
      _msg('Result : '+ writeLifeTime);
     end;
     1:
     begin
     DWord((@fbusreslt[52])^):=ltframe;
     FbusSendSynk;
      _msg('Result : '+WriteLTFbus);
     end;
    end;
   end;
  2:
   begin
    _msg('Writing Block....');
    if not WriteLTnew(sum,2) then _msg('Write data error :(') else
    begin
    _msg('Result : Ok');
    _msg('Restart phone for accept LT changes...');
    end;
   end;
  3:
   begin
    _msg('Writing Block....');
    if not WriteLTnew(sum,3) then _msg('Write data error :(') else
    begin
    _msg('Result : Ok');
    _msg('Restart phone for accept LT changes...');
    end;
   end;
  else
   begin
   _msg('Result : Error');
   end;
  end;
 _msg('Done');
 _msg('');
 SetReady;
end;

procedure TForm1.CalendarbtnClick(Sender: TObject);
var
er           :integer;
k            :word;
Len          :dword;
s, sec       :string;
b            :DWORD;
F            :TFileStream;
Calfile      :system.text;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

 if not Smart then begin
             if datapos='00' then begin
            with SaveDialog do begin
            Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
            +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
            -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
            -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
            FilterIndex:=1;
            FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text)+'_calendar' ;
            InitialDir := '.\';
            DefaultExt := '.txt';
             Filter := 'Series40Calendar(*.event)|*.event|Series40EventPackage(*.evpkg)|*.evpkg';
            FilterIndex:=1;
            Title:='Save Calendar  to ...';
           end;
            if SaveDialog.Execute then begin
              setBuzy;
              case SaveDialog.FilterIndex of
             1:
         begin
            _msg('Backup UserData : [Calendar]');
            _msg('Generation mode : [S40]');
            pb1.Progress:=0;
             _msg('Reading Calendar...');
             er:=PmGetRecCou(51);
             if er<>0 then begin
             pb1.MaxValue:=er;
             _msg(IntToStr(er)+' calendar records are found! Extracting...');
            k:=0;
            System.Assign ( Calfile ,SaveDialog.FileName) ;
            System.Rewrite ( Calfile );
           while er<>0 do begin
             Len:=PmGetRecLen(51,k);
              if Len<>$F0000000 then begin
             s:=PmReadRecordWithOutCheck(51,k,Len);
             S40CalExtr(s);
             if CalRec.Typ='Note' then  System.Writeln(CalFile, (Utf8Decode(IntToStr(k)+' '+CalRec.Typ+' '+CalRec.Date1.Day+'.'+CalRec.Date1.Month+'.'+CalRec.Date1.Year+' '+CalRec.Note)));
             if CalRec.Typ='Call' then System.Writeln(CalFile, (Utf8Decode(IntToStr(k)+' '+CalRec.Typ+' '+CalRec.Date1.Day+'.'+CalRec.Date1.Month+'.'+CalRec.Date1.Year+' '+CalRec.Note+' '+CalRec.Tel)));
             if CalRec.Typ='Birthday' then System.Writeln(CalFile, (Utf8Decode(IntToStr(k)+' '+CalRec.Typ+' '+CalRec.Date1.Day+'.'+CalRec.Date1.Month+'.'+CalRec.DateBeth.Year+' '+CalRec.Note)));
             if CalRec.Typ='Memo' then System.Writeln(CalFile, (Utf8Decode(IntToStr(k)+' '+CalRec.Typ+' '+CalRec.Date1.Day+'.'+CalRec.Date1.Month+'.'+CalRec.Date1.Year+' '+CalRec.Note)));
             if CalRec.Typ='Meeting' then System.Writeln(CalFile, (Utf8Decode(IntToStr(k)+' '+CalRec.Typ+' '+CalRec.Date1.Day+'.'+CalRec.Date1.Month+'.'+CalRec.Date1.Year+' '+CalRec.Note+' '+CalRec.Venue)));
             er:=er-1;
             pb1.Progress:=pb1.Progress+1;
             Application.ProcessMessages;
            end;
            k:=k+1;
           end;
           System.Close(calfile);
           Form1._msg('Calendar saved to : '+SaveDialog.FileName);
           pb1.Progress:=0;
          end
          else begin
           _msg('Calendar is tottaly clear :(');
           SetReady;
           _msg('');
           Exit;
          end;
         end;
         2:
          begin
           pb1.Progress:=0;
           if ScanProcess then begin Application.Terminate; exit; end;
           if not s40drvscan then ReadDataType('EventPackage','C:/Predefcalendar/',SaveDialog.FileName)
           else ReadDataType('EventPackage','S:/Predefcalendar/',SaveDialog.FileName)
          end;
        end;
       end
       else Exit;
     end
     else
     begin
          //  if (datapos='01') or (datapos='11')  then  begin
             with SaveDialog do begin
            Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
            +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
            -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
            -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
            FilterIndex:=1;
            FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text) ;
            InitialDir := '.\';
            DefaultExt := '.event';
            Filter := 'Series40Calendar(*.event)|*.event|Series40EventPackage(*.evpkg)|*.evpkg';
            FilterIndex:=1;
            //'Text file|*.txt|Word file|*.doc';
            Title:='Save Calendar file to ...';
           end;
            if SaveDialog.Execute then
            begin
               SetBuzy;
            case SaveDialog.FilterIndex of
              1:
              begin
               _msg('Backup UserData : [Calendar]');
               _msg('Generation mode : [S40]');
               _msg('Reading Calendar...');
              pb1.Progress:=0;
              if ScanProcess then begin Application.Terminate; exit; end;
              if not s40drvscan then begin
                   //_msg('Using normal S40 algo...');
                   b:=s40getsizeuni('C:/Predefcalendar/event');
                   if b>8 then begin
                   _msg('Found!');
                   M:=TMemoryStream.Create;
                   s40extractuni(M,'C:/Predefcalendar/event',b,1);
                   M.Seek(0,soFromBeginning);
                   if M.Size>0 then begin
                    F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
                    savecalasText(M,copy(SaveDialog.FileName,0,Length(SaveDialog.FileName)-6)+'_calendar.txt');
                    EncryptF(M,F,fullid);
                    F.Free;
                    _msg('File saved to : '+savedialog.FileName);
                   end;
                   M.Free;
                   _msg('Read done ;)');
                end
                else begin
                     _msg('Calendar is tottaly clear :(');
                      SetReady;
                     _msg('');
                      Exit;
                 end;
              end
              else
              begin
                 //_msg('Using New S40 algo...');
                b:=s40getsizeuni('S:/Predefcalendar/event');
                if b>8 then begin
                _msg('File Found!');
                M:=TMemoryStream.Create;
                s40extractuni(M,'S:/Predefcalendar/event',b,1);
                  M.Seek(0,soFromBeginning);
                  if M.Size>0 then begin
                  F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
                  savecalasText(M,copy(SaveDialog.FileName,0,Length(SaveDialog.FileName)-6)+'_calendar.txt');
                  EncryptF(M,F,fullid);
                  F.Free;
                  _msg('File saved to : '+savedialog.FileName);
                  end;
                  M.Free;
                _msg('Read done ;)');
                end
                else begin
                _msg('Calendar is tottaly clear :(');
                SetReady;
                _msg('');
                Exit;
                end;
              end;
             end;
             2:
             begin
              //_msg('Backup UserData : [Event Package]');
              //_msg('Generation mode : [S40]');
              //_msg('Reading Calendar...');
              pb1.Progress:=0;
              if ScanProcess then begin Application.Terminate; exit; end;
              if not s40drvscan then ReadDataType('EventPackage','C:/Predefcalendar/',SaveDialog.FileName)
              else ReadDataType('EventPackage','S:/Predefcalendar/',SaveDialog.FileName)
             End;

            end;
           end
           else exit;
     end;
       _msg('Done!');
       pb1.progress:=0;
       _msg('');
       SetReady;
       Exit;
   end
 else
 begin
     with SaveDialog do begin
        Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
        FilterIndex:=1;
        FileName :=StatusBar.Panels.Items[0].Text+'_'+ RightFileName(StatusBar.Panels.Items[2].Text) ;
        InitialDir := '.\';
        DefaultExt := '.BSPc';
        Filter := 'SmartPhoneCalendar(*.BS60Pc)|*.BS60Pc';
        Title:='Save SmartPhoneCalendar file to ...';
       end;
         if SaveDialog.Execute then begin
         SetBuzy;
        _msg('BackUp UserData : [Calendar]');
        _msg('Generation mode : [S60]');
      if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
       SetMode('Test');
       end;
     /// начнем, пожалуй ;)
      prereadstuff;
      if not startFS60uni then begin
        _msg('FS run fail, please, remove SD card first');
        _msg('Change phone mode manualy to local/test and try again');
        _msg('If still no luck - phone have damaged FS/SD-MMC part..');
        _msg('Done with major error... :(');
        _msg('');
        SetReady;
        Exit;
      end;
      _msg('Fsrun OK...');
      _msg('Detect Symbian OS Generation...');
      if ScanProcess then begin Application.Terminate; exit; end;
      M:=TMemoryStream.Create;
      if not USBS60SecReadData(M,StrToInt(generation),2) then begin
       _msg('Error during read...');
       _msg('');
       M.Free;
       SetReady;
       Exit;
       end
       else begin
       M.Seek(0,soFromBeginning);
       if M.Size>0 then begin
       F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
       EncryptF(M,F,fullid);
       F.Free;
       end;
        M.Free;
       _msg('File saved to : '+savedialog.FileName);
       _msg('Read done ;)');
      end;
         _msg('Done...');
         _msg('');
         pb1.Progress:=0;
         SetReady;
    end
    else exit;
 end;

end;

procedure TForm1.SDpassbtnClick(Sender: TObject);
var
  er,k,len,plen:Integer;
  extr, a, s:string;
  F:TFileStream;
  b:DWORD;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
 if not Smart then begin
   SetBuzy;
    // SetMode('Local');
     pb1.Progress:=0;
    _msg('Reading MMC password...');
       er:=PmGetRecCou(302);
        if er<>0 then begin
        if savepwds40=True then _msg('MMC pass Record found, saving...');
     pb1.MaxValue:=er;
    _msg(IntToStr(er)+' MMC pwd records are found! Extracting...');
    _msg('-------------------------------');
            k:=0;
          while er<>0 do begin
             Len:=PmGetRecLen(302,k);
              if Len<>$F0000000 then begin
             s:=PmReadRecordWithOutCheck(302,k,Len);
             _msg('We have next Pass: '+Utf8Decode(S40PassExtr(s)));
             er:=er-1;
             pb1.Progress:=pb1.Progress+1;
             Application.ProcessMessages;
            end;
            k:=k+1;
          end;
     pb1.Progress:=0;
     _msg('-------------------------------');
     _msg('Done!');
        end else
  _msg('password not set :(');
  _msg('');
  SetReady;
  Exit;
  end
  else begin
     pb1.Progress:=0;
    with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text) ;
       InitialDir := '.\';
       DefaultExt := '.s60pwd';
       Filter := 'SmartPhoneCalendar(*.s60pwd)|*.s60pwd';
       Title:='Save SmartPhonePassword file to ...';
       end;
         if SaveDialog.Execute then begin
       SetBuzy;
     _msg('Searching for MMC pwd...');
     _msg('Generation : [S60]');
     if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
       SetMode('Test');
       end;
       // Понеслась)
       prereadstuff;
        if not startFS60uni then begin
        _msg('FS run fail, please, remove SD card first');
        _msg('Change phone mode manualy to local/test and try again');
        _msg('If still no luck - phone have damaged FS/SD-MMC part..');
        _msg('Done with major error... :(');
        _msg('');
        SetReady;
        Exit;
        end;
       Application.ProcessMessages;
      _msg('Fsrun OK...');
      _msg('Detect Symbian OS Generation...');
      if ScanProcess then begin Application.Terminate; exit; end;
       M:=TMemoryStream.Create;
        if not USBS60SecReadData(M,StrToInt(generation),3) then begin
       _msg('Error during read...');
       _msg('');
       M.Free;
       SetReady;
       Exit;
       end
       else begin
          M.Seek(0,soFromBeginning);
           if M.Size>0 then begin
          _msg('-------------------------------');
          PassStr:=TStringList.Create;
          S60PassExtr(M);
          for er:=0 to PassStr.Count-1 do _msg('We have next Pass: '+Utf8Decode(PassStr.Strings[er]));
          PassStr.Free;
          _msg('-------------------------------');
          end;
       end;
       M.Seek(0,soFromBeginning);
       if M.Size>0 then begin
       F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
       EncryptF(M,F,fullid);
       F.Free;
       end;
        M.Free;
       _msg('File saved to : '+savedialog.FileName);
       _msg('Read done ;)');
      end else exit;

      SetReady;
      _msg('');
      _msg('Done!');
      _msg('');
      pb1.Progress:=0;
    end;
 end;

procedure TForm1.ReadPPBtnClick(Sender: TObject);
var
PPFile:System.Text;
s:string;
i:byte;
j:integer;
TmPP:TStrings;
begin
      with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[0].Text+'_'+StatusBar.Panels.Items[2].Text ;
       InitialDir := '.\';
       DefaultExt := 'pp';
       Filter := 'pp files (*.pp)|*.pp';
       Title:='Save PP file to ...';
      end;
    if SaveDialog.Execute then begin
       SetBuzy;
             System.Assign ( PPFile , SaveDialog.FileName ) ;
             System.Rewrite ( PPFile );
       if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
       SetMode('Test');
       end;
     pb1.MaxValue:=255;
     pb1.Progress:=0;
    _msg('Reading Product Profile sets...');
    _msg('');
    i:=0;
    s:='';
    transid:=$01;
    TmPP:=TStringList.Create;
      while i<>255 do begin
        s:=ReadPPItem(i);
       if s<> 'Error' then begin
         _msg('   '+IntToStr(i)+' - '+s);
         TmPP.Add(IntToStr(i)+' '+s);
         end;
      i:=i+1;
      pb1.Progress:=pb1.Progress+1;
      Application.ProcessMessages;
      end;
      _msg('');
      _msg('SETS 1');
      _msg('Readed '+IntToStr(TmPP.Count)+' element(s)');
      System.Writeln(PPFile,'[Product Profile '+StatusBar.Panels.Items[0].Text+'_'+StatusBar.Panels.Items[2].Text+']');
      System.Writeln(PPFile,'SETS 1');
      System.Writeln(PPFile,'ELEMENTS '+IntToStr(TmPP.Count));
      System.Writeln(PPFile,'');
      System.Writeln(PPFile,'SET 1');
      for j:=0 to TmPP.Count-1 do System.Writeln(PPFile, TmPP.Strings[j]);
      TmPP.Free;
      System.Close ( PPFile );
      _msg('Saved as '+SaveDialog.FileName);
      _msg('');
      _msg('Done!');
      pb1.Progress:=0;
      _msg('');
      _msg(SetReady);
      _msg('');
   end;

end;

procedure TForm1.WritePPBtnClick(Sender: TObject);
var
PPFile:System.Text;
s,st:string;
//i:byte;
j,ele,it:integer;
begin
      with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := 'pp';
       Filter := 'pp files (*.pp)|*.pp';
       Title:='Open PP file ';
      end;
    if OpenDialog.Execute then begin
       SetBuzy;
    System.Assign ( PPFile , OpenDialog.FileName ) ;
    System.Reset(PPFile);
    SetMode('Test');
    _msg('');
    transid:=$01;
    System.Readln(PPFile,s);
    while Copy(s,1,8)<>'ELEMENTS' do System.Readln(PPFile,s);
    ele:=Pos(' ',s)+1;
    s:=Copy(s,ele,Length(s)-ele+1);
    ele:=StrToInt(s);
    pb1.MaxValue:=ele;
    _msg('Write '+s+' element(s)...');
    _msg('');
    System.Readln(PPFile,s);
    while s<>'SET 1' do System.Readln(PPFile,s);
      for j:=1 to ele do begin
       System.Readln(PPFile,s);
       it:=Pos(' ',s);
       st:=Copy(s,1,it-1);
       s:=Copy(s,it+1,Length(s)-it+2);
       _msg('   '+st+' - '+WritePPItem(StrToInt(st),StrToInt(s)));
       pb1.Progress:=pb1.Progress+1;
       Application.ProcessMessages;
      end;
     System.Close ( PPFile );
    _msg('');
    _msg('Done!');
     pb1.Progress:=0;
    _msg('');
    _msg(SetReady);
    _msg('');
    end;
end;

procedure TForm1.WriteRPLbtnClick(Sender: TObject);
var
  RPL:SYSTEM.Text;
  s,a:string;
begin
 SetBuzy;
  with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := 'rpl';
       Filter := 'rpl files (*.rpl)|*.rpl';
       Title:='Open RPL file ';
      end;
       if OpenDialog.Execute then begin
           System.Assign ( RPL , OpenDialog.FileName ) ;
    System.Reset(RPL);
       _msg('Scanning RPL file...');
        System.Readln(RPL,s);
         if Copy(s,1,24)<>'[CERT_PROG_DATA_OUT_CMT]' then begin
           _msg('Scan report : PLAIN RPL Not Found :(');
           end;
       // check for [CERT_PROG_DATA_OUT_CMT] string
        if s='[CERT_PROG_DATA_OUT_CMT]' then begin
       _msg('Rpl is PLAIN type :)');
       _msg('Searching Keys...');
       //
        System.ReadLn(RPL,s);
       while s='NPC_DATA_*' do
       System.ReadLn(RPL,s);
       a:=Copy(s,1,10);
       _Msg(a);


       end;
    System.Close ( RPL );
    end;

    _msg('');
   SetReady;
end;


procedure TForm1.btnADCreadClick(Sender: TObject);
var
  a:string;
begin
  setbuzy;
  _msg('Reading Values...');
  if ConMode=0 then begin
  USBADCread;
  end
  else begin
  _msg('Battery voltage : '+FbusReadBatvalue+' mV');
  _msg('Battery temp : '+rawtotemp(fbusgettemp));
  _msg('Battery size indication : '+inttostr(fbusgetintsize)+'00 Ohm');
  //if not smart then application.ProcessMessages else _msg('System battery volgate : '+inttostr(fbusgetbbat*2)+' mV');
  end;
  _msg('Done!');
  _msg('');

  SetReady;
end;

procedure TForm1.tmClick(Sender: TObject);
var
F:TFileStream;
Len:dword;
begin
// SetBuzy;
  with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\Calendar\';
       DefaultExt := '.event';
       Filter := 'calendar files (*.event)|*.event';
       Title:='Open Calendar file ';
      end;
       if OpenDialog.Execute then begin
        F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
        F.Seek(8,soFromBeginning);
        pb1.MaxValue:=F.Size;
        while F.Position<F.Size do begin
         F.Read(Buf[0],4);
         DwordSwap(@Buf[0]);
         Len:=dword((@Buf[0])^);
         F.Read(Buf[0],Len-4);
         S40NewCalEx ;
             _msg(Utf8Decode(CalRec.Num+' '+CalRec.Typ+' '+CalRec.Date1.Day+'.'+CalRec.Date1.Month+'.'+CalRec.Date1.Year+' '+CalRec.Note));
        pb1.Progress:=F.Position;
        end;
        pb1.Progress:=0;
        F.Free;
       end;
    _msg('');
//   SetReady;
end;

procedure TForm1.DoFormatbtnClick(Sender: TObject);
var
  a,s:string;
  i:integer;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
 if (MessageBox(0, ' Warnig!'+#13+#10+' FileSystem Format - destroy User data in phone permanently!'+#13+#10+' Are You sure?', 'Think, before do..', MB_ICONWARNING or MB_OKCANCEL) in [idOk]) then begin
  setbuzy;
  _msg('Format File System...');
   if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
       SetMode('Local');
       end;
  _msg('Scanning FS parametres...');
  a:=scandrive;
  _msg('Checking Data...');
  Sleep(200);
  Application.ProcessMessages;
  _msg('Detected : '+inttostr(length(a))+' drive(s)...');
  if Length(a)>0 then begin
  _msg('Start formating....');
            if not smart then begin
       _msg('Using Series 40 format algorithm...');
       _msg('==================================');
       for i:=1 to Length(a) do
       begin
         if Pos('S',a)>0 then
           begin
            if a[i]='C' then begin
            if (MessageBox(0, 'Media Memory drive [1Gb] detected!'+#13+#10+'If You format/Repair it - all user data will be destroyed!'+#13+#10+'Format/Repair drive?', 'Media Memory Format Question :', MB_ICONWARNING or MB_YESNO) = idNo) then begin
             _msg('MediaMemory Format aborted by user...');
             _msg('Formating drive : S now...');
                _msg('Step1 : '+ S40formatUni('S'));
                 Sleep(200);
                Application.ProcessMessages;
                _msg('Step2 : '+ S40formatUni('S'));
                Sleep(200);
                Application.ProcessMessages;
                _msg('End format...');
                _msg('==================================');
                _msg('Done!');
                _msg('');
            SetReady;
            Exit;
            end;
            end;
            end;
       _msg('Formating drive : '+a[i]+' now...');
       _msg('Step1 : '+ S40formatUni(a[i]));
        Sleep(200);
        Application.ProcessMessages;
       _msg('Step2 : '+ S40formatUni(a[i]));
        Sleep(200);
        Application.ProcessMessages;
       _msg('End format...');
       _msg('==================================');
       end;
      end
         else begin
        _msg('Using Series 60 format algorithm...');
        _msg('==================================');
        for i:=1 to Length(a) do
       begin
       _msg('Formating drive : '+a[i]+' now...');
       _msg('Step1 : '+S60format(a[i]));
         Sleep(200);
        Application.ProcessMessages;
       _msg('Step2 : '+S60format(a[i]));
         Sleep(200);
        Application.ProcessMessages;
       _msg('End format...');
       _msg('==================================');
     end;
    end;
  end
  else begin
   _msg('Error when init FS!');
   _msg('Change phone mode manualy to local and try again');
   _msg('And don'+#39+'t forget remove SD card before format!!');
   SetReady;
   _msg('');
   Pb1.Progress:=0;
   Exit;
  end;
_msg('Done!');
_msg('');
  Pb1.Progress:=0;
  SetReady;

 end;

end;

procedure TForm1.btnNCKenterClick(Sender: TObject);
begin
if Length(edtNCK.Text)<>15 then begin
_msg('Error! Enter 15 digits of NCK!');
end
 else begin
       SetBuzy;
      _msg('Using F-bus count...');
     _msg('Sending code '+edtNCK.text+' Level : '+cbbLevel.text+' to SimLock Server...');
     if ConMode =0 then  _msg('Simlock Server Answer: '+uncksend(edtNCK.Text,StrToInt(cbbLevel.Text))) else _msg('Simlock Server Answer: '+fncksend(edtNCK.Text,StrToInt(cbbLevel.Text)));
     _msg('Done!');
     _msg('');
     SetReady;
     end;

SetReady;
_msg('');
end;


procedure TForm1.WritePBbtnClick(Sender: TObject);
var
F:TFileStream;
M:TMemoryStream;
co,i,er:integer;
Len:word;
b:DWORD;
s:string;
z:string;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

  if not Smart then begin
      with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := 'S4pb';
        Filter := 'S40 OpenPhoneBook (*.S4pb)|*.S4pb';
       Title:='Open S40 OpenPhoneBook file...';
      end;
    if OpenDialog.Execute then begin
    SetBuzy;
       Application.ProcessMessages;
        _msg('Restoring UserData : [PhoneBook]');
        _msg('Generation mode     : [S40]');
       Application.ProcessMessages;
      if (datapos='11') or (datapos='21') or (datapos='31')then
      begin
       Form1._msg('S40 New Generation Detected');
       if StatusBar.Panels.Items[4].Text<>'Normal' then
       begin
       Form1._msg('Need connect phone in normal mode with Sim-Card');
       form1._msg('After it Connect phone and Write PhoneBook again');
       form1._msg('');
       SetReady;
       exit;
       end;
        case conmode of
       0:GetPBstatus;
       1:Application.ProcessMessages;
       end;
      end
      else SetMode('Local');
    if ScanProcess then begin Application.Terminate; exit; end;
    er:=GetS40PhbCou;
    // _msg('Already present : '+inttostr(er)+' phonebook records...');
      F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
      M:=TMemoryStream.Create;
//      M.LoadFromStream(F);
      DecryptF(F,M,fullid);
      F.Free;
      M.Seek(0,soFromBeginning);
      M.Read(Buf[0],2);
      co:=word((@Buf[0])^);
      pb1.MaxValue:=co;
      _msg('Writing Phonebook...');
      z:=statusbar.panels[1].text;
      for i:=0 to co-1 do begin
        M.Read(Buf[0],2);
        Len:=word((@Buf[0])^);
        M.Read(Buf[2],Len);
        // if ConMode<>0 then FbusSendSynk;
        statusbar.panels[1].text:='Block '+ S40PhbWrite(@Buf[2],Len)+' writen...';
        pb1.Progress:=pb1.Progress+1;
        Application.ProcessMessages;
      end;
      pb1.Progress:=0;
      M.Free;
      _msg(IntToStr(co)+' phonebook records write ok!');
      statusbar.panels[1].text:=z;
      Application.ProcessMessages;
      _msg('Done...');
      _msg('');
    end else exit;
  end
  else begin

        if (ConMode=1) and (Generation='40') then begin
        _msg('WD2 mode autoselected...');
        _msg('Restoring UserData : [PhoneBook]');
        _msg('Generation mode : S60 [WD2]');
        if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
        _msg('Operating mode is OK, no need change...');
         Application.ProcessMessages;
         end
        else begin
        SetMode('Test');
        end;
        WD2RepairPhoneBook;
        _msg('');
        Exit;
      end;

       with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := 'Bs60pb';
        Filter := 'S60 SmartPhoneBook (*.Bs60pb)|*.Bs60pb';
       Title:='Open S60 SmartPhoneBook file...';
      end;
    if OpenDialog.Execute then begin
      SetBuzy;
        _msg('Restoring UserData : [PhoneBook]');
        _msg('Generation mode     : [S60]');
        if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
       SetMode('Test');
       end;
  /// начнем, пожалуй ;)
     prereadstuff;
     if not startFS60uni then begin
        _msg('FS run fail, please, remove SD card first');
        _msg('Change phone mode manualy to local/test and try again');
        _msg('If still no luck - phone have damaged FS/SD-MMC part..');
        _msg('Done with major error... :(');
        _msg('');
        SetReady;
        Exit;
      end;
      _msg('Fsrun OK...');
      _msg('Detect Symbian OS Generation...');
      if ScanProcess then begin Application.Terminate; exit; end;
      case StrToInt(generation) of
     10:  begin
          _msg('Detected: [Symbian OS 9.1/9.2] Phone!');
          _msg(APErunUni);
          _msg('Searching phonebook');
           b:=getsizeS60Uni('C:\Private\100012a5\DBS_100065FF_Contacts.cdb');
          _msg('');
              if b>0 then begin
              _msg('Old data Found!');
               case MessageBox(0, ' Warning! Old data found!'+#13+#10+' If phone after full reset or fullflash - just ignore that message,'+#13+#10+' or You can backup data first...'+#13+#10+' Continue?', 'Rewrite data conformation :', MB_ICONWARNING or MB_YESNO) of
               idYes: begin
                      if ScanProcess then begin Application.Terminate; exit; end;
                      if s60deletefuni('C:\Private\100012a5\DBS_100065FF_Contacts.cdb')=True then _msg('Old data deleted by user request...') else begin
                      _msg('Error! Deleting not possible, try restart phone first!');
                      SetReady;
                      _msg('');
                      Exit;
                      end;
                       end;
               idNo: begin
                     SetReady;
                     _msg('Deleting aborted by user, operating stopped...');
                     _msg('');
                     SetReady;
                     Exit;
                     end;
              end;

            end
            else begin
             _msg('Old phonebook not found, skip earase...');
             end;
            M:=TmemoryStream.Create;
            F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
//            M.LoadFromStream(F);
            DecryptF(F,M,fullid);
            F.Free;
            M.Seek(0,soFromBeginning);
            if ScanProcess then begin Application.Terminate; exit; end;
               if not s60WriteFuni(M,'C:\Private\100012a5\DBS_100065FF_Contacts.cdb',1) then begin
              _msg('Error during write...');
              _msg('');
               M.Free;
              SetReady;
              Exit;
              end
              else begin
              M.Free;
              _msg('');
              _msg('Write done! Please, start phone in normal mode,');
              _msg('And after that enter in phonebook - phone can once time ');
              _msg('Going to reboot - it is normally :)');
              end;
          end;
     1:   begin
           _msg('Detected: [Symbian OS 8.X] Phone!');
           _msg(APErunUni);
           _msg('Searching for phonebook');
             b:=getsizeS60Uni('C:\System\Data\Contacts.cdb');
           _msg('');
            if b<>0 then begin
            _msg('Old data Found!');
             case MessageBox(0, ' Warning! Old data found!'+#13+#10+' If phone after full reset or fullflash - just ignore that message,'+#13+#10+' or You can backup data first...'+#13+#10+' Continue?', 'Rewrite data conformation :', MB_ICONWARNING or MB_YESNO) of
             idYes: begin
                     if ScanProcess then begin Application.Terminate; exit; end;
                      if s60deletefuni('C:\System\Data\Contacts.cdb')=True then _msg('Old data deleted by user request...') else begin
                     _msg('Error! Deleting not possible, try restart phone first!');
                     SetReady;
                     _msg('');
                     Exit;
                     end;
                   end;
             idNo: begin
                   SetReady;
                   _msg('Deleting aborted by user, operating stopped...');
                   _msg('');
                   SetReady;
                   Exit;
                   end;
            end;

           end
           else begin
           _msg('Old phonebook not found, skip earase...');
                end;
           M:=TmemoryStream.Create;
            F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
            DecryptF(F,M,fullid);
            F.Free;
            M.Seek(0,soFromBeginning);
             if ScanProcess then begin Application.Terminate; exit; end;
               if not s60WriteFuni(M,'C:\System\Data\Contacts.cdb',1) then begin
             _msg('Error during write...');
             _msg('');
             M.Free;
             SetReady;
             Exit;
             end
             else begin
             M.Free;
             _msg('');
             _msg('Write done! Please, start phone in normal mode,');
             _msg('And after that enter in phonebook - phone can once time ');
             _msg('Going to reboot - it is normally :)');
             end;

          end;
     11:  begin
          _msg('Detected: [Symbian OS 9.3/9.4] Phone!');
          _msg(APErunUni);
          _msg('Warning! Many [9.3] and [9.4] phones not supported now :(');
          _msg(APErunUni);
           _msg('Searching for phonebook');
             b:=getsizeS60Uni('C:\Private\10003a73\Contacts.cdb');
           _msg('');
            if b<>0 then begin
            _msg('Old data Found!');
             case MessageBox(0, ' Warning! Old data found!'+#13+#10+' If phone after full reset or fullflash - just ignore that message,'+#13+#10+' or You can backup data first...'+#13+#10+' Continue?', 'Rewrite data conformation :', MB_ICONWARNING or MB_YESNO) of
             idYes: begin
                     if ScanProcess then begin Application.Terminate; exit; end;
                      if s60deletefuni('C:\Private\10003a73\Contacts.cdb')=True then _msg('Old data deleted by user request...') else begin
                     _msg('Error! Deleting not possible, try restart phone first!');
                     SetReady;
                     _msg('');
                     Exit;
                     end;
                   end;
             idNo: begin
                   SetReady;
                   _msg('Deleting aborted by user, operating stopped...');
                   _msg('');
                   SetReady;
                   Exit;
                   end;
            end;

           end
           else begin
           _msg('Old phonebook not found, skip earase...');
                end;
           M:=TmemoryStream.Create;
            F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
            DecryptF(F,M,fullid);
            F.Free;
            M.Seek(0,soFromBeginning);
             if ScanProcess then begin Application.Terminate; exit; end;
               if not s60WriteFuni(M,'C:\Private\10003a73\Contacts.cdb',1) then begin
             _msg('Error during write...');
             _msg('');
             M.Free;
             SetReady;
             Exit;
             end
             else begin
             M.Free;
             _msg('');
             _msg('Write done! Please, start phone in normal mode,');
             _msg('And after that enter in phonebook - phone can once time ');
             _msg('Going to reboot - it is normally :)');
             end;
          end;
     end;
    _msg('Done...');
    _msg('');
  end
  else exit;
 end;
 pb1.Progress:=0;
  SetReady;
end;

procedure TForm1.USB1Click(Sender: TObject);
begin
      ConMode:=0;
      if fbdev=1 then
      try
      My_Close_USB_Device;
      except
      Application.ProcessMessages;
      end;
      SelCoMode(ConMode);
end;

procedure TForm1.COM1Click(Sender: TObject);
var
err,i:integer;
s,sn:string;
begin
      if ComSelect.ShowModal =mrOk then begin
       if ComSelect.CoBComList.Items.Count <> 0 then begin
        if Pos ('COM',ComSelect.CoBComList.Items.Strings[ComSelect.CoBComList.ItemIndex])<>0 then begin
          Val(Copy(ComSelect.CoBComList.Items.Strings[ComSelect.CoBComList.ItemIndex],4,2),port,err);
           if fbdev=1 then begin
              try
                Close_USB_Device;
                except
                Application.ProcessMessages;
                end;
                 end;
           fbdev:=0;
           fbnum:=inttostr(port);
        end else if Pos ('UFS',ComSelect.CoBComList.Items.Strings[ComSelect.CoBComList.ItemIndex])<>0 then begin
         s:= ComSelect.CoBComList.Items.Strings[ComSelect.CoBComList.ItemIndex];
         sn:=Copy(s,Pos('S/N ',s)+4,Length(s)-Pos('S/N ',s)+4);
         fbdev:=1;
         fbnum:=sn;
        end;
       end;
      ConMode:=1;
      SelCoMode(ConMode);
      end;
end;

procedure TForm1.InitSgSt(row:integer);
begin
  SelfTest.SgST.RowCount:=row+1;
  SelfTest.Caption:= SelfTest.Caption+'         '+StatusBar.Panels.Items[0].Text+'_'+StatusBar.Panels.Items[2].Text ;
  SelfTest.SgST.Cells[0,0]:='Test Id';
  SelfTest.SgST.Cells[1,0]:='Test Name';
  SelfTest.SgST.Cells[2,0]:='Test Status';
  SelfTest.SgST.Cells[3,0]:='Test Troubleshuting';
end;

procedure TForm1.btnInitClick(Sender: TObject);
var
s,sec   :string;
i,id,st :integer;
sl      :TStrings;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then Application.Terminate;
    sec:=CardPass(crpass);
    if sec <> fullid then Application.Terminate;
    if ScanProcess then begin Application.Terminate; exit; end;
//  {$I crypt_end.inc}
  {$I VM_End.inc}

  SetBuzy;
  sltststart:=0;
  sltstsend:=0;
  sltststart:=Form1.lst1.Items.Count;
_msg('Initializing Tests...');
 {if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
       SetMode('Test');
       end;}
Form1._msg('IMEI : '+form1.statusbar.Panels.Items[2].Text+' , Phone : '+form1.statusbar.Panels.Items[0].Text);
//Form1._msg('FW version : '+form1.statusbar.Panels.Items[1].Text);
_msg('Get keys...');
if conmode=0 then s:=starttest
else
begin
s:=fbuststarttest;
zad:=30;
end;

  sl:=TStringList.Create;
  i:=13;
  while i<Length(s) do begin
   if s[i]=Chr(2) then begin
     i:=i+1;
     st:=Ord(s[i]);
     i:=i+1;
     id:=Ord(s[i]);
     i:=i+1;
     sl.Add(IntToHex(st,2)+'_'+IntToHex(id,2)+':'+Copy(s,i+1,Ord(s[i])-1));
     i:=i+Ord(s[i])-1;
   end;
   i:=i+1;
  end;
   InitSgSt(sl.Count);
  sl.NameValueSeparator:=':';
  for i:=0 to sl.Count-1 do begin
   // _msg(sl.Strings[i]);
    SelfTest.SgST.Cells[0,i+1]:=Copy(sl.Names[i],4,2);
    SelfTest.SgST.Cells[1,i+1]:=sl.ValueFromIndex[i];
    if ConMode=0 then
    begin
      if (Copy(sl.Names[i],4,2)='5B') or (Copy(sl.Names[i],4,2)='50') or (Copy(sl.Names[i],4,2)='4D') or (Copy(sl.Names[i],4,2)='4B') or (Copy(sl.Names[i],4,2)='51') then begin
      Application.ProcessMessages;
      SelfTest.SgST.Cells[2,i+1]:='NOT RUN';
      end
      else
      begin
        SelfTest.SgST.Cells[2,i+1]:=testitemst(Copy(sl.Names[i],4,2));
      end;
    end
    else SelfTest.SgST.Cells[2,i+1]:=testitemst(Copy(sl.Names[i],4,2));

    Application.Processmessages;
    SelfTest.SgST.Cells[3,i+1]:=gettrouble(Copy(sl.Names[i],4,2),SelfTest.SgST.Cells[2,i+1]);
    _msg(SelfTest.SgST.Cells[2,i+1]+' | '+sl.ValueFromIndex[i]);
   Application.ProcessMessages;
   if conmode=0 then sleep(300) else
   begin
   Sleep(500);
   Application.ProcessMessages;
   FbusSendSynk;
   end;
   Application.ProcessMessages;
  end;
  sl.Free;
  for i:=0 to 3 do AutoSizeGridColumn(SelfTest.SgSt,i);
 Application.ProcessMessages;
 Form1._msg('SelfTests end');
 Application.ProcessMessages;
 sltstsend:=Form1.lst1.Items.Count;
 if conmode=1 then
 begin
 Application.Processmessages;
 sleep(500);
 zad:=20;
 end;
  SelfTest.ShowModal;
 {if conmode=1 then begin
 Application.Processmessages;
 _msg('Resetting phone...');
 SetMode('Local');
 _msg('Done!');
 end;    }
 _msg('Done!');
_msg('');
_msg(SetReady);
_msg('');
end;


procedure TForm1.SetPatternbtnClick(Sender: TObject);
var
pat:word;
begin
 SetBuzy;
 setmode('Test');
   case PatternCbox.ItemIndex of
     0:pat:=0;
     1:pat:=$2;
     2:pat:=$9;
     3:pat:=$A;
     4:pat:=$B;
     5:pat:=$C;
     6:pat:=$F;
     7:pat:=$10;
     8:pat:=$17;
     9:pat:=$18;
     10:pat:=$19;
     11:pat:=$1A;
     12:pat:=$1B;
     13:pat:=$1D;
     14:pat:=$1E;
     15:pat:=$3E;
     16:pat:=$3F;
   end;
     _msg(PatternCbox.Items.Strings[PatternCbox.ItemIndex]+' test pattern set - '+LCDSetPat(pat));

 _msg('');
 SetReady;
end;


procedure TForm1.btnWriteCalendarClick(Sender: TObject);
var
  F     :TFileStream;
  ds    :TMemoryStream;
  b     :DWORD;
  s,path:string;
  suc    :Boolean;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
      if not Smart Then begin
      //'00'
     if datapos='00' then
     begin
      {_msg('Sorry, will be support by user request...');
      _msg('');
      exit; }

       with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := '.event';
        Filter := 'Series40EventPackage(*.evpkg)|*.evpkg';
        FilterIndex:=1;
       Title:='Open event file for write ...';
       end;
      if OpenDialog.Execute then
      begin
          SetBuzy;
          _msg('Restoring UserData : [Event Package]');
          _msg('Generation mode    : [S40v1]');
          if ScanProcess then begin Application.Terminate; exit; end;
          F:=TFileStream.Create(OpenDialog.filename,fmOpenRead);
          ds:=TMemoryStream.Create;
          DecryptF(F,ds,fullid);
          f.Free;
          if MyImageWriter(ds)=True then
           form1._msg('Event Package restored')
          else Form1._msg('Event package restore failed :(');
          ds.free;
          _msg('Done');
          _msg('');
          setready;
      end
      else Exit;

     end
     else
     begin
      //'01' and '11' and '21'
      //if (datapos='01') or (datapos='11') then begin
       with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := '.event';
        Filter := 'Series40Calendar(*.event)|*.event|Series40EventPackage(*.evpkg)|*.evpkg';
        FilterIndex:=1;
       Title:='Open event file for write ...';
       end;
      if OpenDialog.Execute then
      begin
          SetBuzy;
       case  OpenDialog.FilterIndex of
          1:
          begin
         _msg('Restoring UserData : [Calendar]');
         _msg('Generation mode    : [S40v2]');
           if ScanProcess then begin Application.Terminate; exit; end;
           if not s40drvscan then path:='C:/Predefcalendar/event' else path:='s:/Predefcalendar/event';
           b:=s40getsizeuni(path);
           if b>0 then
          begin
            changerigts($0020,path);
           if not s40delfileuni(path) then
           begin
           _msg('Error in CS answer!!! Abort operation, Try again');
           _msg('');
           setready;
           exit;
           end;
           _msg('Clear data : Ok');
          end;
          _msg('ReadyForRecive : Ok');
          M:=TmemoryStream.Create;
            F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
            DecryptF(F,M,fullid);
            F.Free;
            M.Seek(0,soFromBeginning);
           if not  S40WriteUni(M,path,1) then
           _msg('Error when writing... :(')
           else  _msg('Succefuly writen! ;)');

          M.Free;
         end;

         2:
         begin
         _msg('Restoring UserData : [Event Package]');
         _msg('Generation mode    : [S40v2]');
          if ScanProcess then begin Application.Terminate; exit; end;
          F:=TFileStream.Create(OpenDialog.filename,fmOpenRead);
          ds:=TMemoryStream.Create;
          DecryptF(F,ds,fullid);
          f.Free;
          if MyImageWriter(ds) then
           form1._msg('Event Package restored')
           else _msg('Event restore failed :(');
         end;

       end;
          _msg('Done!');
          _msg('');
       setready;
      end
      else exit;
     end;

  end
  else begin
          with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
    DefaultExt := '.BS60Pc';
       Filter := 'SmartPhoneCalendar(*.BS60Pc)|*.BS60Pc';
       Title:='Open SmartPhoneCalendar file...';
      end;
   if OpenDialog.Execute then begin
     SetBuzy;
        _msg('Restoring UserData : [Calendar]');
        _msg('Generation mode     : [S60]');
        if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else begin
       SetMode('Test');
       end;
      // go )
      prereadstuff;
      if not startFS60uni then begin
        _msg('FS run fail, please, remove SD card first');
        _msg('Change phone mode manualy to local/test and try again');
        _msg('If still no luck - phone have damaged FS/SD-MMC part..');
        _msg('Done with major error... :(');
        _msg('');
        SetReady;
        Exit;
      end;
      _msg('Fsrun OK...');
      _msg('Detect Symbian OS Generation...');

      if ScanProcess then begin Application.Terminate; exit; end;
       case strtoint(Generation) of
       10: begin
           _msg('Detected: [Symbian OS 9.1/9.2] Phone!');
           _msg(AperunUni);
           _msg('Searching for calendar...');
           b:=getsizeS60Uni('C:\Private\10003a5b\Calendar');
           _msg('');
           if b>0 then begin
           _msg('Old file Found!');
              case MessageBox(0, ' Warning! Old data found!'+#13+#10+' If phone after full reset or fullflash - just ignore that message,'+#13+#10+' or You can backup data first...'+#13+#10+' Continue?', 'Rewrite data conformation :', MB_ICONWARNING or MB_YESNO) of
              idYes:
              begin
                if ScanProcess then begin Application.Terminate; exit; end;
                if s60deletefuni('C:\Private\10003a5b\Calendar')=True then _msg('Old data deleted by user request...') else begin
                _msg('Error! Deleting not possible, try restart phone first!');
                SetReady;
                _msg('');
                Exit;
              end;
              end;
              idNo:
              begin
              SetReady;
              _msg('Deleting aborted by user, operating stopped...');
              _msg('');
              SetReady;
              Exit;
              end;
             end;

             end
             else
             begin
             _msg('Old calendar not found, skip earase...');
              end;
             M:=TmemoryStream.Create;
            F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
            DecryptF(F,M,fullid);
            F.Free;
            M.Seek(0,soFromBeginning);
                if ScanProcess then begin Application.Terminate; exit; end;
                if not s60WriteFuni(M,'C:\Private\10003a5b\Calendar',1) then begin
                _msg('Error during write...');
                _msg('');
                M.Free;
                SetReady;
                Exit;
                end
                else begin
                M.Free;
                _msg('');
                _msg('Write done! Please, start phone in normal mode,');
                _msg('Phone accept changes after few seconds after power on...');
                end;
           end;


       1: begin
          _msg('Detected: [Symbian OS 8.X] Phone!');
          _msg(AperunUni);
          _msg('Searching for calendar...');
           b:=getsizeS60Uni('C:\System\Data\Calendar');
          _msg('');
           if b>0 then begin
             _msg('Old data Found!');
              case MessageBox(0, ' Warning! Old data found!'+#13+#10+' If phone after full reset or fullflash - just ignore that message,'+#13+#10+' or You can backup data first...'+#13+#10+' Continue?', 'Rewrite data conformation :', MB_ICONWARNING or MB_YESNO) of
              idYes:
              begin
               if ScanProcess then begin Application.Terminate; exit; end;
               if s60deletefuni('C:\System\Data\Calendar')=True then _msg('Old data deleted by user request...') else begin
               _msg('Error! Deleting not possible, try restart phone first!');
               SetReady;
               _msg('');
               Exit;
               end;
              end;
              idNo:
              begin
              SetReady;
              _msg('Deleting aborted by user, operating stopped...');
              _msg('');
              SetReady;
              Exit;
              end;
            end;

           end
           else
           begin
           _msg('Old calendar not found, skip earase...');
           end;
           M:=TmemoryStream.Create;
            F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
            DecryptF(F,M,fullid);
            F.Free;
            M.Seek(0,soFromBeginning);
            if ScanProcess then begin Application.Terminate; exit; end;
                if not s60WriteFuni(M,'C:\System\Data\Calendar',1) then begin
                _msg('Error during write...');
                _msg('');
                 M.Free;
                SetReady;
                Exit;
             end
             else begin
             M.Free;
             _msg('');
             _msg('Write done! Please, start phone in normal mode,');
             _msg('Phone accept changes after few seconds after power on...');
            end;
          end;

       11: begin
           _msg('Detected: [Symbian OS 9.3/9.4] Phone!');
           _msg('Warning! Many [9.3] and [9.4] phones not supported now :(');
           _msg('Break on reason : Not yet ;)');
           _msg('');
           SetReady;
           Exit;
           end;
      end;
  _msg('Done...');
  _msg('');
  SetReady;
  end
  else exit;
 end;
  pb1.Progress:=0;
end;


procedure TForm1.btnLightClick(Sender: TObject);
begin
Light('on');
end;

procedure TForm1.TimLicTimer(Sender: TObject);
label tmrm;
var
s,sk,st,l:string;
F: TFileStream;
M:TMemoryStream;
i:integer;
begin
    if not connect then begin Application.Terminate; goto tmrm; end;
    if not LicExists then begin
          TimLic.Enabled := false ;
          s:= GetFullId ;
          l:='license_best_'+s+'.ask';
          AboutBox1.Edit1.Text:=s;
          if infinity then begin
           AboutBox1.Label1.Caption:='Please, fill this form and send the created file';
           AboutBox1.Label2.Caption:=l+' on e-mail';
           AboutBox1.Label4.Caption:='               support@bb5tool.com';
           AboutBox1.Label4.Font.Color:=clBlue;
          end;
          AboutBox1.ShowModal ;
          if ( AboutBox1.Edit2.Text ='') or (AboutBox1.Edit3.Text ='' ) then begin
                _msg('Required field not filed !!! ');
                Application.Terminate;
                goto tmrm;
                end;
          s:= AboutBox1.Edit1.Text+Chr($0)+AboutBox1.Edit2.Text+Chr($0)+AboutBox1.Edit3.Text+Chr($0);
       if not infinity then s:=Chr($FF)+s;
       i:= Length(s) mod 8;
       if i<>0 then SetLength(s,Length(s)+8-i);
           i:=1;
           sk:='';
           while i < Length(s)-1 do begin
           st:=Copy(s,i,8);
           sk:=sk+CardCrypt(st);
           i:=i+8;
           end;
       F:=TFileStream.Create(l,fmCreate);
       F.Write(sk[1],Length(sk));
       F.Free;
          _msg('file '+'.\'+l+' created - OK');
       if infinity then
       begin
        ShowMessage('Send '+l+' file to support@bb5tool.com');
       Application.Terminate;
       goto tmrm;
       end;

       M:=TMemoryStream.Create;
       F:=TFileStream.Create(ChangeFileExt(l,'.dat'),fmCreate);
//      _msg('http://www.bb5tool.com/lic/dongle.php?data='+BufToHexStr(@sk[1],Length(sk)));
      if not GetInetFile('http://www.bb5tool.com/lic/dongle.php?data='+BufToHexStr(@sk[1],Length(sk)),M) then
       begin
        ShowMessage('Server return error message, send '+l+' file to support@bb5tool.com manuale');
        Application.Terminate;
        goto tmrm;
       end;
      if M.Size <32 then begin
        ShowMessage('Server return error message, send '+l+' file to support@bb5tool.com manuale');
        Application.Terminate;
        goto tmrm;
       end;
      M.Seek(0,soFromBeginning);
      s:='';
      SetLength (s,M.Size);
      M.Read(s[1],M.Size);
      M.Free;
      sk:='';
      SetLength(sk,((Length(s) shr 1)));
      i:=StrToBufHex(s,@sk[1]);
      F.Write(sk[1],Length(sk));
       F.Free;
       ShowMessage('The license file is successfully received! Please restart software.');
       Application.Terminate;
       end ;
tmrm:

end;
procedure TForm1.DecryptF(strmInput,strmOutput:TStream;key:string);
var
  Cipher: TDCP_cipher;         // the cipher to use
  CipherIV: array of byte;     // the initialisation vector (for chaining modes)
  Hash: TDCP_hash;             // the hash to use
  HashDigest: array of byte;   // the result of hashing the passphrase with the salt
  Salt: array[0..7] of byte;   // a random salt to help prevent precomputated attacks
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    strmOutput.Seek(0,soFromBeginning);
    strmInput.Seek(0,soFromBeginning);
    Hash := DCP_sha11;
    SetLength(HashDigest,Hash.HashSize div 8);
    strmInput.ReadBuffer(Salt[0],Sizeof(Salt));  // read the salt in from the file
    Hash.Init;
    Hash.Update(Salt[0],Sizeof(Salt));   // hash the salt
    Hash.UpdateStr(key);  // and the passphrase
    Hash.Final(HashDigest[0]);           // store the hash in HashDigest
    Cipher := DCP_3des1;
    if (Cipher is TDCP_blockcipher) then            // if it is a block cipher we need the IV
    begin
      SetLength(CipherIV,TDCP_blockcipher(Cipher).BlockSize div 8);
      strmInput.ReadBuffer(CipherIV[0],Length(CipherIV));       // read the initialisation vector from the file
      Cipher.Init(HashDigest[0],Min(Cipher.MaxKeySize,Hash.HashSize),CipherIV);  // initialise the cipher
      TDCP_blockcipher(Cipher).CipherMode := cmCBC;
    end
    else
      Cipher.Init(HashDigest[0],Min(Cipher.MaxKeySize,Hash.HashSize),nil);  // initialise the cipher
    Cipher.DecryptStream(strmInput,strmOutput,strmInput.Size - strmInput.Position); // decrypt!
    Cipher.Burn;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
end;


procedure TForm1.EncryptF(strmInput,strmOutput:TStream;key:string);
var
  Cipher: TDCP_cipher;         // the cipher to use
  CipherIV: array of byte;     // the initialisation vector (for chaining modes)
  Hash: TDCP_hash;             // the hash to use
  HashDigest: array of byte;   // the result of hashing the passphrase with the salt
  Salt: array[0..7] of byte;   // a random salt to help prevent precomputated attacks
  i: integer;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    strmOutput.Seek(0,soFromBeginning);
    strmInput.Seek(0,soFromBeginning);
    Hash := DCP_sha11;
    SetLength(HashDigest,Hash.HashSize div 8);
    for i := 0 to 7 do
      Salt[i] := Random(256);  // just fill the salt with random values (crypto secure PRNG would be better but not _really_ necessary)
    strmOutput.WriteBuffer(Salt,Sizeof(Salt));  // write out the salt so we can decrypt!
    Hash.Init;
    Hash.Update(Salt[0],Sizeof(Salt));   // hash the salt
    Hash.UpdateStr(key);  // and the passphrase
    Hash.Final(HashDigest[0]);           // store the output in HashDigest
    Cipher := DCP_3des1;
    if (Cipher is TDCP_blockcipher) then      // if the cipher is a block cipher we need an initialisation vector
    begin
      SetLength(CipherIV,TDCP_blockcipher(Cipher).BlockSize div 8);
      for i := 0 to (Length(CipherIV) - 1) do
        CipherIV[i] := Random(256);           // again just random values for the IV
      strmOutput.WriteBuffer(CipherIV[0],Length(CipherIV));  // write out the IV so we can decrypt!
      Cipher.Init(HashDigest[0],Min(Cipher.MaxKeySize,Hash.HashSize),CipherIV);  // initialise the cipher with the hash as key
      TDCP_blockcipher(Cipher).CipherMode := cmCBC;   // use CBC chaining when encrypting
    end
    else
      Cipher.Init(HashDigest[0],Min(Cipher.MaxKeySize,Hash.HashSize),nil); // initialise the cipher with the hash as key
    Cipher.EncryptStream(strmInput,strmOutput,strmInput.Size); // encrypt the entire file
    Cipher.Burn;   // important! get rid of keying information
//    {$I crypt_end.inc}
  {$I VM_End.inc}
end;

function TForm1.Min(a, b: integer): integer;
begin
  if (a < b) then
    Result := a
  else
    Result := b;
end;


procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
setini:TIniFile;
begin
          freeLibrary ( hndDLLHandle );
          setini:=TIniFile.Create(ExtractFileDir(Application.ExeName)+'\settings.ini');
          setini.WriteInteger('core','TbSel',pgc1.TabIndex);
          setini.WriteString('prddir','1',prd1);
          setini.WriteString('prddir','2',prd2);
          setini.WriteString('prddir','3',prd3);
          setini.WriteInteger('prddir','ch',phsel);
          setini.WriteInteger('core','ConMod',0);
          setini.WriteInteger('core','FbDev',fbdev);
          setini.WriteString('core','FbNum',fbnum);
          setini.WriteBool('core','UsIni',Usini.Checked);
          setini.WriteBool('core','ManFl',FlMan.Checked);
          setini.Free;

          MC.Free;
          //TimConChk.Enabled:=False;
          //TimOfClock.Enabled:=false;
          VplList.Free;
          PurgeCom(PURGE_TXCLEAR or PURGE_RXCLEAR);
          Purge_USB_Device_IN;
          Purge_USB_Device_OUT;
          CloseCom;
          Close_USB_Device;
          ConMode:=0;
          Sleep(500);
          Application.Terminate;
end;

procedure TForm1.Exit1Click(Sender: TObject);
var
setini:TIniFile;
begin
          freeLibrary ( hndDLLHandle );
          if StatusBar.Panels.Items[6].Text ='BUZY' then while StatusBar.Panels.Items[6].Text ='BUZY' do;
          setini:=TIniFile.Create(ExtractFileDir(Application.ExeName)+'\settings.ini');
          setini.WriteInteger('core','TbSel',pgc1.TabIndex);
          setini.WriteString('prddir','1',prd1);
          setini.WriteString('prddir','2',prd2);
          setini.WriteString('prddir','3',prd3);
          setini.WriteInteger('prddir','ch',phsel);
          setini.WriteInteger('core','ConMod',0);
          setini.WriteInteger('core','FbDev',fbdev);
          setini.WriteString('core','FbNum',fbnum);
          setini.WriteBool('core','UsIni',Usini.Checked);
          setini.WriteBool('core','ManFl',FlMan.Checked);
          setini.Free;
          SetBuzy;
          MC.Free;
         // TimConChk.Enabled:=False;
         // TimOfClock.Enabled:=false;
          VplList.Free;
          PurgeCom(PURGE_TXCLEAR or PURGE_RXCLEAR);
          Purge_USB_Device_IN;
          Purge_USB_Device_OUT;
          Close_USB_Device;
          CloseCom;
          ConMode:=0;
          Sleep(500);
          Application.ProcessMessages;
          Application.Terminate;
end;

procedure Tform1.afterFlashdo();  //Post-Flashing-овые операции
var
  a    : string;
  i,xt : integer;
  pctext : string;
begin

  if (chkCheckRead.Checked=True) or (chkReseLt.checked=true) or (ChkAFFset.checked=true) or (chkBootNormal.checked=true) then begin

  if chkCheckRead.Checked=True then
  begin
   if not ReadPhoneInfo then _msg('Error when try read Phone info... :(')
   else begin
    _msg('Reading Phone Info....');
    _msg('Connected phone -   '+PhInfoRecord.Name);
    _msg('Software Info:     '+PhInfoRecord.MCUSW);
    _msg('IMEI:  '+PhInfoRecord.IMEIPlain);
    if PhInfoRecord.APECoreSW<>'' then _msg('Ape Version: '+PhInfoRecord.APECoreSW);
    if PhInfoRecord.APEVariant<>'' then  _msg('APE Variant:  '+PhInfoRecord.APEVariant);
    if PhInfoRecord.PPMInfo<>'' then _msg('PPM version :   '+PhInfoRecord.PPMInfo);
    _msg('Product code:  '+PhInfoRecord.ProductCode);
    _msg('Checking...');
      Application.ProcessMessages;
      sleep(50);
      Application.ProcessMessages;
      sleep(50);
      a:='';
      xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('21');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

      if a='PASSED' then Form1._msg('SimLock status : SimLock is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('SimLock status : Can'+#39+'t get status ') else Form1._msg('SimLock status : SimLock Damaged!!!!! :('); end;
      Application.ProcessMessages;
      sleep(50);
      a:='';

      xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('5D');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=10);

      if a='PASSED' then Form1._msg('Security status : Security is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('Security status : Can'+#39+'t get status ') else Form1._msg('Security status : Security Damaged!!!!! :(') end;
      a:='';
      Application.ProcessMessages;
      //_msg('SDD Key status : '+checkSD);
    _msg('Read Info Done!');
   end;
  end;

  if ChkAFFset.checked=true then begin
   _msg('Settings After Flash Defaults...');
   if (chkCNTe.Checked=True) or (chkAPEe.Checked=True) or (chkCnt3.Checked=True) then begin
   if ConMode=1 then FbusSendSynk;
   if not FullFactorySet then  _msg('Error When resetting FullFactory :( ...') else  _msg('FullFactorySet...OK!');
   end;
   if ConMode=1 then FbusSendSynk;
   If not PrdTuneSet then
   begin
   _msg('Error When resetting Product Tune :( ...');
   Application.ProcessMessages;
   end
   else _msg('ProductTuneSet...OK!');
   if ConMode=1 then FbusSendSynk;
    if not SWupgrDef then begin
     _msg('Error When resetting SW upgrade Default :( ...');
    Application.ProcessMessages;
    end
     else _msg('SwUpgradeSet...OK!');

  end;

 { if chkRestoreData.checked=true then begin
    _msg('Restoring User data....');
    _msg('Restore: '+RestoreUserData);
  end;   }

   if chkChPC.checked=true then
   begin

   if UsIni.Checked=true then begin
    if cbbSelPC.text<>'' then pctext:=Copy(cbbSelPC.Text,1,7);
    case ConMode of
    1: begin
       fbuswriteprdcode(pctext);
       Form1._msg('Product code update...');
       end;
    0: begin
           i:=1;
           while i<8 do
           begin
           WriteProductCode[15+i]:=ord(pctext[i]);
           inc(i);
           end;
           PrdCodewrite;
           Form1._msg('Product code update...');
       end;
    end;

   end;
  end;

   if chkReseLt.checked=true then begin
    try
    form1._msg('Resetting LifeTimer');
     case ConMode of
     0:resetLTnew;
     1:if PmWriteRecord(88,0,'000000000000000000000000000000000000000000000000000000000000000000000000')<>'Error' then form1._msg('Reset Done!')
       else form1._msg('Reset Error!');
     end;
    except
    Application.ProcessMessages;
    end;
  end;

   if ConMode=1 then Sleep(500);
   if ConMode=1 then FbusSendSynk;
   RM:=s40pref;
   checkini;
   try
   if Generation='00' then repairusercert;
   except
   Form1._msg('FS damaged, or minor error');
   end;

  if ConMode=0  then begin
   if chkBootNormal.checked=true then begin
    _msg('Set phone to Normal mode...');
      ResetPhone;
    for i:=0 to 20 do
    begin
    Application.ProcessMessages;
    Sleep(100);
    Application.ProcessMessages;
    end;
    _msg('AfterFlash operations done...');
    Exit;
   end;
  end;
  _msg('AfterFlash operations done... Reconnect, wait...');
 end
 else begin
  _msg('Afterflash not selected, skip');
 end;
end;

procedure TForm1.btnFLASHClick(Sender: TObject);
var  i                : integer;
     b,swchk          : Boolean;
     s,md             : string;
     x                : Integer;
     batval           : integer;
     cs               : Byte;
     scanbyte         : integer;
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

  if btnFLASH.caption='Stop'
  then
  begin
   case MessageBox(0, 'Do You want BREAK OPERATION??? '+#13+#10+'IT CAN DAMAGE PHONE IN SOME CASES!!!!'+#13+#10+''+#13+#10+'Press Yes to Break, No to continue...', 'BREAK OPERATION', MB_ICONWARNING or MB_YESNO) of
    idYes :
     begin
       stop:=True;
       btnFLASH.caption:='FLASH';
     end;
    idNo  : Application.ProcessMessages;
   end;
  Exit;
  end;

  case ConMode of
  1: DisUfsButton;
  0: Application.ProcessMessages;
  end;
   stop:=false;
   btnFLASH.caption:='Stop';
 if (ConMode=1) and (fbdev=1) then
 begin
    scanbyte:=0;
    Form1._msg('Selected FlashSettings : '+cbbModeFlash.text);
    FselectFlashMode;

    if readset('stuff','FAsk')=True then begin
     if (MessageBox(0, 'Are You sure of right choose files? IT must be RM-Correct! '+#13+#10+'If All rigth - Press - Ok.'+#13+#10+
     'DOWNGRADE can kill phone - remember that...', 'Before Flash confirm...', MB_ICONWARNING or MB_OKCANCEL) <> idOk) then
     begin
     if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     Setready;
     Exit;
     end;
    end;
   Filepresent;    // чекаем наличие файлов выбранных - есть ли они вообще
   Application.ProcessMessages;

      Application.ProcessMessages;
     _msg('Files Set for Flashing :');
     if (core<>'') and (chkMCUen.checked=true) then _msg('MCU : '+ExtractFileName(core));
     if (ppm<>'') and (chkPPMe.Checked=True) then _msg('PPM : '+ExtractFileName(ppm));
     if (ppm1<>'') and (chkPPM1e.Checked=True) then _msg('PPM2 : '+ExtractFileName(ppm1));
     if (image<>'') and (chkCNTe.Checked=True) then _msg('CNT : '+ExtractFileName(image));
     if (ape<>'') and (chkAPEe.Checked=True) then _msg('APE : '+ExtractFileName(ape));
     if (cnt3<>'') and (chkCnt3.Checked=True) then _msg('CNT3 : '+ExtractFileName(cnt3));
   // _msg('Flashing phone now...');
     Application.ProcessMessages;

    if (core='') and (ppm='') and (ppm1='') and (image='') and (ape='') and (cnt3='')
    then
    begin
    Form1._msg('');
    Form1._msg('Flash files not selected!!! Break...');
    Form1._msg('');
    SetReady;
    exit;
    end;
    
   Application.ProcessMessages;
   if core<>'' then
      if BB5ScanHeader(core)=$A then Inc(scanbyte);
   if ppm<>'' then
      if BB5ScanHeader(ppm)=$A then Inc(scanbyte);
   if image<>'' then
      if BB5ScanHeader(image)=$A then Inc(scanbyte);
   Application.ProcessMessages;
   if scanbyte>0 then
  begin
   setbuzy;
   disableFLtab;
   Form1._msg('');
   Form1._msg('Infineon flashing...');
   Application.ProcessMessages;
   SwitchBoxMode('FBUS');
   Application.ProcessMessages;
   setbuzy;
   Application.ProcessMessages;
   if not Boot_infineon then
   begin
   Form1._msg('Boot failed, phone not found');
   Form1._msg('-> Try again few times, check cable');
   Form1._msg('-> Try start flashing and insert cable in box during boot');
   Form1._msg('');
   SetReady;
   exit;
   end;
   Application.ProcessMessages;
   if not BusCheckInfineon then
   begin
   form1._msg('Error booting phone...');
   form1._msg('-> Try again few times, check cable');
   form1._msg('');
   SetReady;
   Exit;
   end;
   Application.ProcessMessages;
   form1.statusbar.Panels.Items[4].text:='FLASHING';
   if (core<>'') and (MCUt.Text<>'') and (chkMCUen.Checked=True) then
   begin
    Form1._msg('   ===Flashing [MCU]===');
    if not FlashInfineonFile(core) then
    begin
    form1._msg('Error...');
    form1._msg('-> Check cable, flashfile');
    Form1._msg('');
    SetReady;
    Exit;
    end;
   end;
   Application.ProcessMessages;
   if (ppm<>'') and (PPMt.Text<>'') and (chkPPMe.Checked=True) then
   begin
    Form1._msg('   ===Flashing [PPM]===');
    if not FlashInfineonFile(ppm) then
    begin
    form1._msg('Error...');
    form1._msg('-> Check cable, flashfile');
    Form1._msg('');
    SetReady;
    Exit;
    end;
   end;
   Application.ProcessMessages;
   if (image<>'') and (CNTt.Text<>'') and (chkCNTe.Checked=True) then
   begin
    Form1._msg('   ===Flashing [CNT]===');
    if not FlashInfineonFile(image) then
    begin
    form1._msg('Error...');
    Form1._msg('');
    SetReady;
    Exit;
    end;
   end;
   Application.ProcessMessages;
    InfineonEnd;
    Form1._msg('');
    Form1._msg('Flashing done, rebooting...');
    Form1._msg('-> Infineon info : Do FullFactory Sets after flashing');
    Form1._msg('Flashing Done!');
    Form1._msg('');
    //DisconnectFill;
    switchboxmode('FBUS');
    if (chkAFFset.Checked=True) or (chkCheckRead.Checked=true) then
    begin
     if not InitServiceMode then
     begin
     Form1._msg('Init service mode failed!');
     Form1._msg('Try powerup phone manually and connect');
     Form1._msg('');
     end
     else
     begin
      //setmode('Test');
       for i:=0 to 35 do Sleep(100);
      Form1._msg('Afterflash settings...');
      Application.ProcessMessages;
      if chkCheckRead.Checked=True then
      begin
      ReadPhoneInfo;
      Application.ProcessMessages;
      //if PhInfoRecord.Name<>'Error' then Form1._msg('Phone  : '+PhInfoRecord.Name);
      Form1._msg('SW ver : '+PhInfoRecord.MCUSW);
      Form1._msg('IMEI   : '+PhInfoRecord.IMEIPlain);
      Form1._msg('PCode  : '+PhInfoRecord.ProductCode);
      //Form1._msg('');
      end;
      if ChkAFFset.checked=true then
      begin
       _msg('Settings After Flash Defaults...');
       Application.ProcessMessages;

       FbusSendSynk;
       if not FullFactorySet then
       _msg('Error When resetting FullFactory :( ...')
       else  _msg('FullFactorySet...OK!');
       Application.ProcessMessages;
       FbusSendSynk;
       If not PrdTuneSet then
       _msg('Error When resetting Product Tune :( ...')
       else _msg('ProductTuneSet...OK!');
       Application.ProcessMessages;
       FbusSendSynk;
       if not SWupgrDef then
        _msg('Error When resetting SW upgrade Default :( ...')
        else _msg('SwUpgradeSet...OK!');
       Application.ProcessMessages;
      end;
      Form1._msg('All done!');
      Form1._msg('');
      DisconnectFill;
      {Application.ProcessMessages;
      busreset;
      Set_USB_Device_TimeOuts($2710,$2710);
      Application.ProcessMessages;  }
      SwitchBoxMode('FBUS');
     end;
    end;
    SetReady;
   Exit;
  end;


    if readset('verify','Flverify')=True then
   begin
   _msg('Check FlashFiles, Please, wait...');
     if not checkFlFiles then
     begin
     _msg('Bad Flash files detected, will break procedure :(');
     _msg('');
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     Setready;
     Exit;
    end;
   end
   else _msg('FlashFile verify disabled');

  if (PhonePresentmode=$01) and (UsIni.Checked=true) and (FlMan.checked=false) and (chkMCUen.checked=true) then
  begin
   if checkSWver=false then
   begin
    case chkDOWNGRADE.checked of
     false : Application.ProcessMessages;
     True  : begin
             _msg('->  Downgrade not need, disable downgrade');
              if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
             end;
    end;
   end
   else
   begin
     case chkDOWNGRADE.checked of
     false : begin

              case MessageBox(0, 'Downgrade try detected, but downgrade not enabled!'+#13+#10+'It will kill phone.'+#13+#10+'Enabled downgrade? '+#13+#10+'If no - flashing will be stopped.', 'Downgrade detected!', MB_ICONWARNING or MB_OKCANCEL) of
              idOk: begin
                    chkDowngrade.checked:=true;
                    _msg('->  Downgrade enabled by user request')
                    end;
              idCancel: begin
                     _msg('->  Downgrade detected, flash breaked by user');
                     _msg('');
                     if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
                     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                     Setready;
                     enableFLtab;
                     exit;
                     end ;
              end;

             end;
     True  : Application.ProcessMessages;
    end;
   end;
  end
  else
  begin
   if FlMan.checked=true then md:='Manual';
   if UserIn.checked=true then md:='UserIni';
   if chkMCUen.checked=False then md:='Custom';
   if PhonePresentmode=$00 then md:='Dead';
   Form1._msg('-> SWversion check skipped : '+md+' mode selected');
   Form1._msg('');
  end;
   setbuzy;
    UFSFlashing;
   setready;
    Exit;
    //hhh
 end;
   //if fbdev=0 then exit;

  Setbuzy;
  swchk:=False;
  x:=0;
  md:='';
     msgid:=$1B;

     Form1._msg('Selected FlashSettings : '+cbbModeFlash.text);
     FselectFlashMode;

     if readset('stuff','FAsk')=True then
     begin
     if (MessageBox(0, 'Are You sure of right choose files? '+#13+#10+'If All rigth - Press - Ok.'+#13+#10+
     'DOWNGRADE can kill phone - remember that...', 'Before Flash confirm...', MB_ICONWARNING or MB_OKCANCEL) <> idOk) then
     begin
     if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     Setready;
     Exit;
     end;
     end;
   Filepresent;    // чекаем наличие файлов выбранных - есть ли они вообще
   Application.ProcessMessages;
   if readset('verify','Flverify')=True then
   begin
   _msg('Check FlashFiles, Please, wait...');
    if not checkFlFiles then
    begin
     _msg('Bad Flash files detected, will break procedure :(');
     _msg('');
     if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     Setready;
     Exit;
    end;
   end
   else _msg('FlashFile verify disabled');

   _msg('');
   Application.ProcessMessages;
   
     if  core=''  then
     begin
          _msg('->  Flash Files are NOT selected!');
          _msg('      You can Select:');
          _msg('      S40     : Any, but MCU need present in filelist');
          _msg('      S60     : Any, but CORE/MCU need present in filelist');
          _msg('      S60 APE : MCU+PPM, MCU+PPM+CNT');
          _msg('');
     if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     Setready;
     Exit;
     end;

   Application.ProcessMessages;
   _msg('Files Set for Flashing :');
     if (core<>'') and (chkMCUen.checked=true) then _msg('MCU : '+ExtractFileName(core));
     if (ppm<>'') and (chkPPMe.Checked=True) then _msg('PPM : '+ExtractFileName(ppm));
     if (ppm1<>'') and (chkPPM1e.Checked=True) then _msg('PPM2 : '+ExtractFileName(ppm1));
     if (image<>'') and (chkCNTe.Checked=True) then _msg('CNT : '+ExtractFileName(image));
     if (ape<>'') and (chkAPEe.Checked=True) then _msg('APE : '+ExtractFileName(ape));
     if (cnt3<>'') and (chkCnt3.Checked=True) then _msg('CNT3 : '+ExtractFileName(cnt3));
  _msg('Flashing phone now...');
  Application.ProcessMessages;

  x:=Bb5scanheader(core);
  Application.ProcessMessages;
  _msg('Check files done...');
  disableFLtab;  // отключаем часть интерфейса - чтоб не жмакали лишний раз при прошивке.

  if (UsIni.Checked=true) and (FlMan.checked=false) and (chkDEADMODE.checked=false) and (chkMCUen.checked=true) then
  begin
   if checkSWver=false then
    begin
    case chkDOWNGRADE.checked of
     false : Application.ProcessMessages;
     True  : begin
             _msg('->  Downgrade not need, disable downgrade');
              if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
             end;
    end;
   end
   else
   begin
     case chkDOWNGRADE.checked of
     false : begin

              case MessageBox(0, 'Downgrade try detected, but downgrade not enabled!'+#13+#10+'It will kill phone.'+#13+#10+'Enabled downgrade? '+#13+#10+'If no - flashing will be stopped.', 'Downgrade detected!', MB_ICONWARNING or MB_OKCANCEL) of
              idOk: begin
                    chkDowngrade.checked:=true;
                    _msg('->  Downgrade enabled by user request')
                    end;
              idCancel: begin
                     _msg('->  Downgrade detected, flash breaked by user');
                     _msg('');
                     if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
                     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                     Setready;
                     enableFLtab;
                     exit;
                     end ;
              end;

             end;
     True  : Application.ProcessMessages;
    end;
   end;
  end
  else begin
   if FlMan.checked=true then md:='Manual';
   if UserIn.checked=true then md:='UserIni';
   if chkMCUen.checked=False then md:='Custom';
   if chkDEADMODE.checked=true then md:='Dead';
   Form1._msg('-> SWversion check skipped : '+md+' mode selected');
  end;
  case x of
  1,3 : begin

      if core='' then begin
      _msg('');
      _msg('-> Flash Files are NOT selected!');
      _msg('     You can Select:');
      _msg('     MCU, PPM, CNT, MCU+PPM, MCU+CNT, MCU+PPM+CNT...');
      _msg('');
      if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
      if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
      Setready;
      enableFLtab;
      exit;
      end; 

      if chkMCUen.checked=false then begin
       if chkDEADMODE.Checked=True then begin
       _msg('-> Custom flashing in dead mode active!');
       _msg('-> Phone will boot in normal mode after flash!');
       end;
      end;

     Application.ProcessMessages;

     if not chkDEADMODE.Checked then begin
      if not chkDOWNGRADE.Checked then
      begin
          if chkBackup.checked=true then
          begin
               _msg('Backup CRT308 data...');
               _msg(CRT308backup);
                 case chksl of
               1:Application.ProcessMessages;
                2,3:
                begin
                RPLRClear;
                RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
                RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
                RPLRecord.WMDRM_PD:=BackupKey('WDRM');
                writeRpl(PhInfoRecord.IMEIPlain);
                end;
               end;
               // _msg('Continue flashing...');
          end;
      end
      else
      begin
          _msg('Backup CRT308 data...');
          _msg(CRT308backup);
           case chksl of
               1:Application.ProcessMessages;
                2,3:
                begin
                RPLRClear;
                RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
                RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
                RPLRecord.WMDRM_PD:=BackupKey('WDRM');
                writeRpl(PhInfoRecord.IMEIPlain);
                end;
               end;
       end;
       if not Smart then
       begin
       if savepwds40=True then form1._msg('->  MMC pass Record found, saving...');
        end;
     Application.ProcessMessages;
     batval:=StrToInt(UsbReadBatvalue);
      if batval<3800 then begin
       _msg('Batery valtage : '+inttostr(batval)+' mV');
       case MessageBox(0, 'Batery voltage is low!!! ( less than 3,8V )'+#13+#10+'Do you want continue?', 'Batery voltage check', MB_ICONWARNING or MB_OKCANCEL) of
       idOk: begin
             _msg('-> Batery voltage less, than 3,8V ('+inttostr(batval)+'mV). Continue at user risk');
             end;

       idCancel: begin
                  _msg('-> Batery voltage is low, please, charge');
                  _msg('      Break by user request');
                  _msg('');
                  repairdata;
                  if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                  Setready;
                  enableFLtab;
                  exit;
                 end ;
       end;
       end;
     end;
     form1.btnFLASH.enabled:=True;
     _msg('Getting product info...');

     if x=3 then oldsmart:=True else oldsmart:=False;

     if chkDEADMODE.Checked=false then b:=BB5_NormalFlashing
     else
     begin
          Form1.StatusBar.Panels.Items[6].Text :='DEAD';
          b:=BB5_DEADFlashing(0);
     end;

     if Not b then begin
     _msg('->  Error while flashing... :(');
     _msg('');
     repairdata;
     if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     Setready;
     enableFLtab;
     //DisconnectFill;
     exit;
    end;
     repairdata;
     _msg('');
     _msg(Setready);
     cltrycn.ShowBalloonHint('BB5 Easy Service Tool Flashing','Flashing done',bitinfo,10);
     _msg('');
     enableFLtab;
     DisconnectFill;
     Application.ProcessMessages;
   end;

   2: begin
   msgid:=$0F;
   Form1.S60flash;
   end;
   
   4,8,6: begin
     if chkDeadMode.Checked=true then begin
     _msg('');
     _msg('-> That PhoneType are NOT support DEAD MODE flashing!');
     _msg('');
     chkDEADMODE.Checked:=False;
     setready;
     enableFLtab;
     Exit;
     end;

     if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('');
     _msg('->  APE devices are not support boot in test\local mode!');
     _msg('      Do all backup operation, and after do reset\format ');
     _msg('      PowerUp phone in normal mode for flashing');
     _msg('');
     enableFLtab;
     if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
     SetReady;
     Exit;
     end;

     if chkDowngrade.checked=true then begin
     _msg('->  Downgrade attempt for APE phone detected');
        case MessageBox(0, 'Downgrade just kill your phone....'+#13+#10+'Continue flashing?', 'Downgrade try', MB_ICONWARNING or MB_YESNO) of
        idYes: Application.ProcessMessages;

        idNo: begin
                enableFLtab;
                if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                _msg('->  Downgrade aborted by user');
                _msg('->  Break flashing procedure...');
                _msg('');
                SetReady;
                Exit;
              end;
        end;
      _msg('-> Continue by user request...');
      if Not downgradeprep then
            begin
           _msg('');
           SetReady;
           Exit;
           end ;
      end;

      batval:=StrToInt(UsbReadBatvalue);
      if batval<3800 then begin
       _msg('Batery valtage : '+inttostr(batval)+' mV');
       case MessageBox(0, 'Batery voltage is low!!! ( less than 3,8V )'+#13+#10+'Do you want continue?', 'Batery voltage check', MB_ICONWARNING or MB_OKCANCEL) of
       idOk: begin
             _msg('-> Batery voltage less, than 3,8V ('+inttostr(batval)+'mV). Continue at user risk');
             end;

       idCancel: begin
                  _msg('-> Batery voltage is low, please, charge');
                  _msg('      Break by user request');
                  _msg('');
                  repairdata;
                  if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                  Setready;
                  enableFLtab;
                  exit;
                 end ;
       end;
       end;
      Application.ProcessMessages;
   msgid:=$0F;
   form1.btnFLASH.enabled:=True;
   Form1.OmapBootFlash;
   end;

    5: // RAPUYAMA/RAP3Gv4 flashing mode
   begin
      if core='' then begin
      _msg('');
      _msg('-> Flash Files are NOT selected!');
      _msg('     You can Select:');
      _msg('     Any, but MCU/CORE need present in filelist');
      _msg('');
      if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
      if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
      Setready;
      enableFLtab;
      exit;
      end;
        case chkDEADMODE.Checked of
        false:
        begin
          if chkBackup.checked=true then
          begin
               RPLRClear;
               _msg('Backup CRT308 data...');
               _msg(CRT308backup);
               RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
               RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
               RPLRecord.WMDRM_PD:=BackupKey('WDRM');
          end;
         _msg('Check communication with phone....');
          cs:=s60checkadl;
          case cs of
          $07 :
           begin
           _msg('ADL req restart');
           _msg('Communication verify done... Preparing...');
           TransId:=$5E; MsgBody:=$0A;
           Application.ProcessMessages;
           if Smart then s60preflashread;

           b:=true;
        //RootHash
          // for i := 0 to $0F do b:=b and (RAPInfo.Root_Key_Hash[i]<>0);
          if BufToHexStr(@RAPInfo.Root_Key_Hash[0],$0F)='00000000000000000000000000000000' then b:=False;
          if Not b then
          begin
          _msg('->  No RootKey Asic! (IMEI DAMAGED?) Unable to continue flashing...');
          enableFLtab;
          SetReady;
          _msg('');
          exit;
          end;
          _msg('Gathering phone info...');
          Application.ProcessMessages;
         // Form1._msg('RAP_BOOT:     '      + BufToHexStr(@RAPInfo.BootID[0],      Length(RAPInfo.BootID)));
         // Form1._msg('RAP_PUBLIC:   '    + BufToHexStr(@RAPInfo.PublicID[0],    Length(RAPInfo.PublicID)));
         // Form1._msg('CMT_ROOTKEY:  '  + BufToHexStr(@RAPInfo.Root_Key_Hash[0], Length(RAPInfo.Root_Key_Hash)));
         // Form1._msg('RAP_PAPUBKEY: '  + BufToHexStr(@RAPInfo.PAPUBKEYSID[0], Length(RAPInfo.PAPUBKEYSID)));
          _msg('Check communication with phone...');
          if s60checkadl<>$07 then begin
          _msg('->  Error while checking phone... Try Flash again...');
          _msg('      Flashing failed...');
          enableFLtab;
          SetReady;
          _msg('');
          exit;
          end;

          batval:=StrToInt(UsbReadBatvalue);
          if batval<3800 then begin
          _msg('Batery valtage : '+inttostr(batval)+' mV');
           case MessageBox(0, 'Batery voltage is low!!! ( less than 3,8V )'+#13+#10+'Do you want continue?', 'Batery voltage check', MB_ICONWARNING or MB_OKCANCEL) of
             idOk: begin
             _msg('-> Batery voltage less, than 3,8V ('+inttostr(batval)+'mV). Continue at user risk');
             end;

             idCancel: begin
                  _msg('-> Batery voltage is low, please, charge');
                  _msg('      Break by user request');
                  _msg('');
                  repairdata;
                  if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                  Setready;
                  enableFLtab;
                  exit;
                 end ;
            end;
           end;
           Application.ProcessMessages;
         
		      if chkDowngrade.checked=true then begin
         _msg('->  Downgrade attempt detected');
          case MessageBox(0, 'Downgrade just kill your phone....'+#13+#10+'Continue flashing?', 'Downgrade try', MB_ICONWARNING or MB_YESNO) of
           idYes: Application.ProcessMessages;

           idNo: begin
                enableFLtab;
                if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                _msg('->  Downgrade aborted by user');
                _msg('->  Break flashing procedure...');
                _msg('');
                SetReady;
                Exit;
              end;
            end;
         _msg('-> Continue by user request...');
         end;

         Application.ProcessMessages;
         _msg('Reboot....');
         Application.ProcessMessages;
       form1.btnFLASH.enabled:=True;
       if not ADLBootInFlash then begin
       _msg('->  Error rebooting phone... Try Flash again...');
       _msg('    Flashing failed...');
       SetReady;
       enableFLtab;
       _msg('');
       exit;
       end;

       if not ExtractloaderXSRRap3Gv4(0) then
                              begin
                                _msg('->  Boot fail...');
                                _msg('    Flashing failed...');
                                SetReady;
                                _msg('');
                                enableFLtab;
                                exit;
                              end;
      BB5_FlashingXSR16;
      _msg('');
      enableFLtab;
      _msg(setready);
      cltrycn.ShowBalloonHint('BB5 Easy Service Tool Flashing','Flashing done',bitinfo,10);
      Application.ProcessMessages;
      DisconnectFill;
      if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
      Exit;
      end;
     else
       begin
       _msg('->  Unknow ADL state['+byte2str(cs)+']... Sorry, continue impossible... :(');
       _msg('    Flashing failed...');
       _msg('');
       enableFLtab;
       SetReady;
       Exit;
       end;
     end;
    end;
    true:
     begin
       try
       form1.btnFLASH.enabled:=True;
       RPLRClear;
       except
       Application.ProcessMessages;
       form1.btnFLASH.enabled:=True;
       RPLRClear;
       end;
     if not ExtractloaderXSRRap3Gv4(1) then
                              begin
                                _msg('->  Boot fail...');
                                _msg('    Flashing failed...');
                                SetReady;
                                if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
                                _msg('');
                                enableFLtab;
                                exit;
                              end;
       BB5_FlashingXSR16;
       _msg('');
       _msg(setready);
       cltrycn.ShowBalloonHint('BB5 Easy Service Tool Flashing','Flashing done',bitinfo,10);
       enableFLtab;
       DisconnectFill;
       if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
       Exit;
       end;

    end;
   end;
   9: // Nomadic
   begin
   if core='' then begin
      _msg('');
      _msg('-> Flash Files are NOT selected!');
      _msg('     You can Select:');
      _msg('     Any, but MCU/CORE need present in filelist');
      _msg('');
      if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
      if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
      Setready;
      enableFLtab;
      exit;
      end;
        case chkDEADMODE.Checked of
        false:
        begin
          if chkBackup.checked=true then
          begin
               _msg('Backup CRT308 data...');
               _msg(CRT308backup);
               RPLRClear;
               RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
               RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
               RPLRecord.WMDRM_PD:=BackupKey('WDRM');
               writeRpl(PhInfoRecord.IMEIPlain);
          end;
         _msg('Check communication with phone....');
          cs:=s60checkadl;
          case cs of
          $08 :
           begin
           form1.btnFLASH.enabled:=True;
           _msg('ADL req restart');
           _msg('Communication verify done... Preparing...');
           TransId:=$5E; MsgBody:=$0A;
           Application.ProcessMessages;
           if Smart then s60preflashread;

           b:=true;
        //RootHash
          // for i := 0 to $0F do b:=b and (RAPInfo.Root_Key_Hash[i]<>0);
          if BufToHexStr(@RAPInfo.Root_Key_Hash[0],$0F)='00000000000000000000000000000000' then b:=False;
          if Not b then
          begin
          _msg('->  No RootKey Asic! (IMEI DAMAGED?) Unable to continue flashing...');
          enableFLtab;
          SetReady;
          _msg('');
          exit;
          end;
          _msg('Gathering phone info...');
          Application.ProcessMessages;
         // Form1._msg('RAP_BOOT:     '      + BufToHexStr(@RAPInfo.BootID[0],      Length(RAPInfo.BootID)));
         // Form1._msg('RAP_PUBLIC:   '    + BufToHexStr(@RAPInfo.PublicID[0],    Length(RAPInfo.PublicID)));
         // Form1._msg('CMT_ROOTKEY:  '  + BufToHexStr(@RAPInfo.Root_Key_Hash[0], Length(RAPInfo.Root_Key_Hash)));
         // Form1._msg('RAP_PAPUBKEY: '  + BufToHexStr(@RAPInfo.PAPUBKEYSID[0], Length(RAPInfo.PAPUBKEYSID)));
          _msg('Check communication with phone...');
          if s60checkadl<>$08 then begin
          _msg('->  Error while checking phone... Try Flash again...');
          _msg('      Flashing failed...');
          enableFLtab;
          SetReady;
          _msg('');
          exit;
          end;

          batval:=StrToInt(UsbReadBatvalue);
          if batval<3800 then begin
          _msg('Batery valtage : '+inttostr(batval)+' mV');
           case MessageBox(0, 'Batery voltage is low!!! ( less than 3,8V )'+#13+#10+'Do you want continue?', 'Batery voltage check', MB_ICONWARNING or MB_OKCANCEL) of
             idOk: begin
             _msg('-> Batery voltage less, than 3,8V ('+inttostr(batval)+'mV). Continue at user risk');
             end;

             idCancel: begin
                  _msg('-> Batery voltage is low, please, charge');
                  _msg('      Break by user request');
                  _msg('');
                  repairdata;
                  if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                  Setready;
                  enableFLtab;
                  exit;
                 end ;
            end;
           end;
           Application.ProcessMessages;

		      if chkDowngrade.checked=true then begin
         _msg('->  Downgrade attempt detected');
          case MessageBox(0, 'Downgrade just kill your phone....'+#13+#10+'Continue flashing?', 'Downgrade try', MB_ICONWARNING or MB_YESNO) of
           idYes: Application.ProcessMessages;

           idNo: begin
                enableFLtab;
                if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                _msg('->  Downgrade aborted by user');
                _msg('->  Break flashing procedure...');
                _msg('');
                SetReady;
                Exit;
              end;
            end;
         _msg('-> Continue by user request...');
         end;

         Application.ProcessMessages;
         _msg('Reboot....');
         Application.ProcessMessages;

       if not ADLBootInFlash then begin
       _msg('->  Error rebooting phone... Try Flash again...');
       _msg('    Flashing failed...');
       SetReady;
       enableFLtab;
       _msg('');
       exit;
       end;
       starttime;
       if not NomandicBoot(0) then
                              begin
                                _msg('->  Boot fail...');
                                _msg('    Flashing failed...');
                                SetReady;
                                _msg('');
                                enableFLtab;
                                exit;
                              end;
       endtimecount;
       _msg('TIME : Boot time : '+showtime(tmsres)+' ');
       BB5_Flashingnomadic;
       _msg('');
       enableFLtab;
       _msg(setready);
       cltrycn.ShowBalloonHint('BB5 Easy Service Tool Flashing','Flashing done',bitinfo,10);
       Application.ProcessMessages;
       DisconnectFill;
       if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
       Exit;
      end;
     else
       begin
       _msg('->  Unknow ADL state['+byte2str(cs)+']... Sorry, continue impossible... :(');
       _msg('    Flashing failed...');
       _msg('');
       enableFLtab;
       SetReady;
       Exit;
       end;
     end;
    end;
    true:
     begin
     starttime;
     form1.btnFLASH.enabled:=True;
     if not NomandicBoot(1) then
                              begin
                                _msg('->  Boot fail...');
                                _msg('    Flashing failed...');
                                SetReady;
                                if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
                                _msg('');
                                enableFLtab;
                                exit;
                              end;
       endtimecount;
       _msg('TIME : Boot time : '+showtime(tmsres)+' ');
       BB5_FlashingNomadic;
       _msg('');
       _msg(setready);
       cltrycn.ShowBalloonHint('BB5 Easy Service Tool Flashing','Flashing done',bitinfo,10);
       enableFLtab;
       DisconnectFill;
       if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
       Exit;
       end;

    end;
   end;
 else
   begin
   _msg('->  Sorry, can'+#39+'t flash it now - please send report to support' );
   if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
   _msg('');
   enableFLtab;
   SetReady;
   Exit;
   end;
 end;
 enableFLtab;
end;


procedure TForm1.SelMCUClick(Sender: TObject);
begin
setbuzy;
core:='';
     with OpenDialog do
     begin
          Options:=Options+[ofFileMustExist]-[ofHideReadOnly]+[ofNoChangeDir]
                          -[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
                          -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
                          -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
          FilterIndex:=1;
          FileName :='';
          InitialDir := '.\';
          DefaultExt := 'mcusw';
          Filter := 'Core files (*.mcusw)|*.mcusw*;|All files (*.*)|*.*';
          Title:='Open Core file';
     end;
     if not OpenDialog.Execute then
     begin
          setready;
          TimConChk.Enabled:=true;
          exit;
     end;
     core:=OpenDialog.FileName;
     MCUt.Text:=ExtractFileName(Opendialog.FileName);
     _msg('MCU: '+ExtractFileName(Opendialog.FileName));
     SetReady;
end;


procedure TForm1.selPPMClick(Sender: TObject);
begin
  ppm:='';
 with OpenDialog do
     begin
          Options:=Options+[ofFileMustExist]-[ofHideReadOnly]+[ofNoChangeDir]
                          -[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
                          -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
                          -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
          FilterIndex:=1;
          FileName :='';
          InitialDir := '.\';
          DefaultExt := 'ppm';
          Filter := 'PPM files (*.ppm)|*.ppm*;|All files (*.*)|*.*';
          Title:='Open PPM file';
     end;
     if not OpenDialog.Execute then
     begin
          setready;
          TimConChk.Enabled:=true;
          exit;
     end;
     ppm:=OpenDialog.FileName;
     PPMt.Text:=ExtractFileName(Opendialog.FileName);
     _msg('PPM: '+ExtractFileName(Opendialog.FileName));
     SetReady;
end;

procedure TForm1.bselCNTClick(Sender: TObject);
begin
    image:='';
     with OpenDialog do
     begin
          Options:=Options+[ofFileMustExist]-[ofHideReadOnly]+[ofNoChangeDir]
                          -[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
                          -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
                          -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
          FilterIndex:=1;
          FileName :='';
          InitialDir := '.\';
          DefaultExt := 'image';
          Filter := 'Content files (*.image)|*.image*;|All files (*.*)|*.*';
          Title:='Open Image file';
     end;
     if not OpenDialog.Execute then
     begin
          setready;
          TimConChk.Enabled:=true;
          exit;
     end;
     image:=OpenDialog.FileName;
     CNTt.Text:=ExtractFileName(Opendialog.FileName);
     _msg('CNT: '+ExtractFileName(Opendialog.FileName));
     SetReady;
end;

function TForm1.RightFileName(const FileName: string):string;
var
  I: integer;
begin
  Result:='';
  for I := 1 to Length(FileName) do
   if ((FileName[i]='?') or (FileName[i]='''') or (FileName[i]='"') or (FileName[i]='<') or (FileName[i]='>') or (FileName[i]='|')) then Result:=Result+'x' else Result:=Result+Filename[i];
end;

procedure TForm1.SaUsArClick(Sender: TObject);
label retry;
var
i,Len,flen       :integer;
path,fpath,tpath :String;
FL               :TStrings;
i2,ercnt         :integer;
F                :TFileStream;
s                :string;
ret:integer;
begin
  {$I VM_Start.inc}
//   {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

  if SaUsAr.caption='Stop' then
  begin
  stop:=True;
  Exit;
  end;

  SaUsAr.caption:='Stop';
   SetBuzy;
  Application.ProcessMessages;
  SaUsAr.enabled:=True;
   flen:=0;
   FL:=TStringList.Create;
   if not smart then begin
    _msg('BackUp UserData : [Gallery]');
    _msg('Generation mode : [S40]');
      if not s40drvscan then path:=Utf8Encode('c:\predefgallery\') else path:=Utf8Encode('c:\');
   //_msg('List of '+path+' directory');
   _msg('Scanning FileSystem..');
   //_msg(GetUsbDir(path));
   if ScanProcess then begin Application.Terminate; exit; end;
   GetS40FileList(FL,path);
   _msg('Scan done, processing data...');
   _msg('Total - '+IntToStr(FL.Count)+' files');
       pb1.maxvalue:=FL.Count;
       Application.ProcessMessages;

     for i:=0 to FL.Count-1 do begin
      len:=0;
      if stop=True then
      begin
      dostop('SAVE GALLERY');
      Application.ProcessMessages;
      fl.Free;
      form1.pb1.progress:=0;
      form1.pbsm1.progress:=0;
      setready;
      Exit;
      end;
       // Len:=StrToInt(Copy(FL.Strings[i],1,(Pos(':',FL.Strings[i])-1)));
      fpath:=FL.Strings[i];
           //_msg('Reading');
           //_msg(IntToStr(Len));
           //_msg(Utf8Decode(fpath));
           //_msg('');
      tpath:=fpath;
      Delete(fpath,1,3);
      path:='.\'+StatusBar.Panels.Items[2].Text+'\'+Utf8ToAnsi(fpath);
          //_msg(tpath);
          //if not DirectoryExists(ExtractFilePath(path)) then CreateDir(ExtractFilePath(path));
     // try
       Len:=s40getsizeuni(tpath);
       //_msg(IntToStr(Len));
       if Len>0 then
       begin
        flen:=flen+len;
        M:=TmemoryStream.Create;
        if not s40extractuni(M,tpath,Len,2) then
         begin
         goto retry;
         retry :
         case MessageBox(0, 'Read error detected!'+#13+#10+''+#13+#10+'Looks like connection lost.'+#13+#10+'Please - Repower/Reconnect phone and press Retry.'+#13+#10+''+#13+#10+'Also You can Ignore that error or cancel reading.', 'Read Error', MB_ICONWARNING or MB_ABORTRETRYIGNORE) of
         idAbort: begin
                  FL.free;
                  _msg('Aborted by User...');
                  _msg('');
                  form1.pb1.progress:=0;
                  form1.pbsm1.progress:=0;
                  setready;
                  exit;
                  end;
         idRetry: begin
                   case ConMode of
                   0:
                    begin
                     _msg('Try again.... (wait 10 sec)');
                      ret:=0;
                      repeat
                      Application.ProcessMessages;
                      sleep(20);
                      inc(ret);
                      until (ret=500) or (catchdevice=$01);
                      if ret<>500 then
                      begin
                      if not s40extractuni(M,tpath,Len,2)
                      then goto retry;
                      end
                      else
                      begin
                       FL.free;
                       _msg('Connection with phone lost... Abort procedure... :(');
                       _msg('');
                       form1.pb1.progress:=0;
                       form1.pbsm1.progress:=0;
                       setready;
                       exit;
                       end;
                    end;
                    1:
                    begin
                      _msg('Try again.... (wait 5 sec)');
                      ret:=0;
                      repeat
                      Application.ProcessMessages;
                      sleep(10);
                      inc(ret);
                      until ret=500;
                     FbusSendSynk;
                     if not s40extractuni(M,tpath,Len,2)
                     then  goto retry;
                    end;
                   end;
                  end;
         idIgnore: begin
                    case ConMode of
                    0:
                    begin
                      _msg('Ignore Read Error... (wait 10 sec)');
                     ret:=0;
                     repeat
                     Application.ProcessMessages;
                     sleep(20);
                     inc(ret);
                     until (ret=500) or (catchdevice=$01);
                     if ret<>500 then Application.ProcessMessages
                     else
                     begin
                     FL.free;
                       _msg('Connection with phone lost... Abort procedure... :(');
                       _msg('');
                       form1.pb1.progress:=0;
                       form1.pbsm1.progress:=0;
                       setready;
                       exit;
                     end;
                    end;
                    1:
                    begin
                     _msg('Ignore Read Error... (wait 5 sec)');
                     ret:=0;
                     FbusSendSynk;
                     repeat
                     Application.ProcessMessages;
                     sleep(10);
                     inc(ret);
                     until (ret=500);
                     Fbussendsynk;
                    end;
                   end;
                  end;
         end;
         end;
        M.Seek(0,soFromBeginning);
        if M.Size>0 then begin
        try
        F:=TFileStream.Create(RightFileName(path),fmCreate);
        F.CopyFrom(M,M.Size);
        F.Free;
        except
        F:=TFileStream.Create('.\'+rightfilename(StatusBar.Panels.Items[2].Text)+'\'+extractfilename(tpath),fmCreate);
        F.CopyFrom(M,M.Size);
        F.Free;
        end;
        end;
        M.Free;
       end;
     // except
     //  _msg('Error while reading file! Attempt to continue...');
     //  Application.ProcessMessages;
     // end;

       pb1.progress:=pb1.progress+1;
       //sleep(200);
    end;
   end else begin
     if Generation='01' then begin
       path:=Utf8Encode('C:\Nokia\');
       end
       else begin
   path:=Utf8Encode('C:\Data\');
   //path:=Utf8Encode('C:\');
   end;
     // _msg('List of '+path+' directory');
     // _msg('');

        _msg('BackUp UserData : [Gallery]');
        _msg('Generation mode : [S60]');
        if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else SetMode('Test');

  /// начнем, пожалуй ;)
     prereadstuff;
      if not startFS60uni then begin
        _msg('FS run fail, please, remove SD card first');
        _msg('Change phone mode manualy to local/test and try again');
        _msg('If still no luck - phone have damaged FS/SD-MMC part..');
        _msg('Done with major error... :(');
        _msg('');
        SetReady;
        Exit;
      end;
      _msg('Fsrun OK...');
      _msg(AperunUni);


   //   _msg(GetUsbDir(path));

      GetS60FileList(FL,path);
   //_msg('');
   _msg('Total - '+IntToStr(FL.Count)+' files');
   Form1.pb1.maxvalue:=FL.Count;
   _msg('Reading, wait....');
       Application.ProcessMessages;

   for i:=0 to FL.Count-1 do begin
    len:=0;
    if stop=True then
      begin
      dostop('SAVE GALLERY');
      Application.ProcessMessages;
      fl.Free;
      form1.pb1.progress:=0;
      form1.pbsm1.progress:=0;
      setready;
      Exit;
      end;
    // Len:=StrToInt(Copy(FL.Strings[i],1,(Pos(':',FL.Strings[i])-1)));
     fpath:=FL.Strings[i];
           // _msg('Reading');
          //   _msg(IntToStr(Len));
         // _msg(Utf8Decode(fpath));
   tpath:=fpath;
   Delete(fpath,1,3);
    path:='.\'+StatusBar.Panels.Items[2].Text+'\'+Utf8ToAnsi(fpath);
       //   _msg(path);
       //    if not DirectoryExists(ExtractFilePath(path)) then CreateDir(ExtractFilePath(path));
    //if ConMode=0 then begin
        Len:=getsizeS60Uni(tpath);
        if Len>0 then begin
        flen:=flen+len;
        M:=TmemoryStream.Create;
        S60extractuni(M,tpath,Len,2);
        M.Seek(0,soFromBeginning);
        try
        if M.Size<>0 then begin
        F:=TFileStream.Create(RightFileName(path),fmCreate);
        F.CopyFrom(M,M.Size);
        F.Free;
        Application.ProcessMessages;
        end;
        M.Free;
        except
        _msg('Error while creating file! Attempt to continue...');
        Application.ProcessMessages;
        end;
      end
      else
      begin
      _msg('Error on CS packet! Skipping...');
      Application.Processmessages;
      end;

   // end;

    pb1.progress:=pb1.progress+1;
//   sleep(200);
   end;
   end;
   calcsize(flen);
  _msg ('Read Done !');
  _msg ('');
   pb1.MaxValue:=100;
   pb1.Progress:=0;
   FL.Free;
   _msg(SetReady);
  _msg ('');
end;

procedure TForm1.GetS60FileList(FL:TStrings;path:string);
label a1;
var
DL:TStrings;
i,co,Len,ln,j,k:integer;
s,a:string;
begin
   if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text)) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text));
   DL:=TStringList.Create;
   DL.Add(path);
 while DL.Count<>0 do begin
  //_msg(DL.Strings[0]);
  CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text+Utf8ToAnsi(Copy(DL.Strings[0],3,Length(DL.Strings[0])-3))));
//  _msg ('.\'+StatusBar.Panels.Items[2].Text+Utf8ToAnsi(Copy(DL.Strings[0],3,Length(DL.Strings[0])-3)));
   if ConMode =0 then begin
    a:=UsbS60ListFile(DL.Strings[0]);
    co:=rxBuf[11];
    if co=0 then goto a1;
    i:=12;
    while co<>0 do begin
    i:=i+5;
    Len:=byte((@rxBuf[i])^);
    i:=i+20;
    ln:=rxBuf[i];
    i:=i+1;
    j:=i;
    s:='';
    k:=0;
          while k<>ln do begin
          WordSwap(@rxBuf[i]);
          i:=i+2;
          k:=k+1;
          end;
          SetLength(s,255);
          j:=UnicodeToUtf8(@s[1],255,@rxBuf[j],ln);
          SetLength(s,j-1);
//      _msg(BufToHexStr(@s[1],Length(s)));
          if ((Len>=$20) and (Len<$30)) then s:=s+Chr($5C);
          s:= DL.Strings[0]+s;
//      _msg(Utf8Decode(s));
         if (ln and 1)=0 then i:=i+2;
          if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);
    co:=co-1;
    end;
   end else begin
    a:=FbusS60ListFile(DL.Strings[0]);
    co:=Ord(FBusStr[6]);
    if co=0 then goto a1;
    i:=7;
    while co<>0 do begin
    i:=i+5;
    Len:=byte((@FBusStr[i])^);
    i:=i+20;
    ln:=Ord(FBusStr[i]);
    i:=i+1;
    j:=i;
    s:='';
    k:=0;
          while k<>ln do begin
          WordSwap(@FBusStr[i]);
          i:=i+2;
          k:=k+1;
          end;
          SetLength(s,255);
          j:=UnicodeToUtf8(@s[1],255,@FBusStr[j],ln);
          SetLength(s,j-1);
//      _msg(BufToHexStr(@s[1],Length(s)));
          if ((Len>=$20) and (Len<$30)) then s:=s+Chr($5C);
          s:= DL.Strings[0]+s;
//      _msg(Utf8Decode(s));
         if (ln and 1)=0 then i:=i+2;
          if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);
    co:=co-1;
    end;
   end;

  while a<>'' do begin
    if ConMode =0 then begin
    a:=UsbS60ContList(DL.Strings[0]);
    co:=rxBuf[11];
    i:=12;
    while co<>0 do begin
    i:=i+5;
    Len:=byte((@rxBuf[i])^);
    i:=i+20;
    ln:=rxBuf[i];
    i:=i+1;
    j:=i;
    s:='';
    k:=0;
          while k<>ln do begin
          WordSwap(@rxBuf[i]);
          i:=i+2;
          k:=k+1;
          end;
          SetLength(s,255);
          j:=UnicodeToUtf8(@s[1],255,@rxBuf[j],ln);
          SetLength(s,j-1);
//      _msg(BufToHexStr(@s[1],Length(s)));
          if ((Len>=$20) and (Len<$30)) then s:=s+Chr($5C);
          s:= DL.Strings[0]+s;
 //     _msg(Utf8Decode(s));
         if (ln and 1)=0 then i:=i+2;
          if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);
    co:=co-1;
    end;
    end else begin
     a:=FbusS60ContList(DL.Strings[0]);
    co:=Ord(FBusStr[6]);
    i:=7;
    while co<>0 do begin
    i:=i+5;
    Len:=byte((@FBusStr[i])^);
    i:=i+20;
    ln:=Ord(FBusStr[i]);
    i:=i+1;
    j:=i;
    s:='';
    k:=0;
          while k<>ln do begin
          WordSwap(@FBusStr[i]);
          i:=i+2;
          k:=k+1;
          end;
          SetLength(s,255);
          j:=UnicodeToUtf8(@s[1],255,@FBusStr[j],ln);
          SetLength(s,j-1);
//      _msg(BufToHexStr(@s[1],Length(s)));
          if ((Len>=$20) and (Len<$30)) then s:=s+Chr($5C);
          s:= DL.Strings[0]+s;
//      _msg(Utf8Decode(s));
         if (ln and 1)=0 then i:=i+2;
          if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);
    co:=co-1;
    end;
    end;
       Application.ProcessMessages;
  end;
a1:

   DL.Delete(0);
 end;
   DL.Free;
end;

procedure TForm1.GetS40FileList(FL:TStrings;path:string);
var
DL:TStrings;
i:integer;
s,a:string;
begin
   if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text)) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text));
   DL:=TStringList.Create;
   DL.Add(path);
 while DL.Count<>0 do begin
  //_msg(DL.Strings[0]);
  CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text+Utf8ToAnsi(Copy(DL.Strings[0],3,Length(DL.Strings[0])-3))));
//  _msg ('.\'+StatusBar.Panels.Items[2].Text+Utf8ToAnsi(Copy(DL.Strings[0],3,Length(DL.Strings[0])-3)));
   if ConMode =0 then s:=UsbS40ListFile(DL.Strings[0]) else s:=FbusS40ListFile(DL.Strings[0]);
    if s<>'' then if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);

  while s<>'' do begin
   if ConMode =0 then s:=UsbS40ContList(DL.Strings[0]) else s:=FbusS40ContList(DL.Strings[0]);
  // _msg(Utf8Decode(s));
   if s<>'' then if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);
   Application.ProcessMessages;
  end;
   DL.Delete(0);
 end;
   DL.Free;
end;

procedure TForm1.SilentGetS40FileList(FL:TStrings;path:string);
var
DL:TStrings;
i:integer;
s,a:string;
begin
   //if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text)) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text));
   DL:=TStringList.Create;
   DL.Add(path);
 while DL.Count<>0 do begin
  //_msg(DL.Strings[0]);
  //CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text+Utf8ToAnsi(Copy(DL.Strings[0],3,Length(DL.Strings[0])-3))));
//  _msg ('.\'+StatusBar.Panels.Items[2].Text+Utf8ToAnsi(Copy(DL.Strings[0],3,Length(DL.Strings[0])-3)));
   if ConMode =0 then s:=UsbS40ListFile(DL.Strings[0]) else s:=FbusS40ListFile(DL.Strings[0]);
    if s<>'' then if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);

  while s<>'' do begin
   if ConMode =0 then s:=UsbS40ContList(DL.Strings[0]) else s:=FbusS40ContList(DL.Strings[0]);
  // _msg(Utf8Decode(s));
   if s<>'' then if Ord(s[Length(s)])<>$5C then FL.Add(s) else DL.Add(s);
   Application.ProcessMessages;
  end;
   DL.Delete(0);
 end;
   DL.Free;
end;

procedure TForm1.btnUSEiniClick(Sender: TObject);
label select;
var
  s,currprdpath:string; //текущий путь продукт с которым будем работать
  SearchRec:TSearchRec;
  VplList:TStrings;
  i,cou:integer;
begin
  currproduct:='';
 if statusbar.Panels[0].text='' then begin
  _msg('Using Manual selecting mode...');
  PrdSelect.Show;
 end
 else begin
   SetBuzy;
   cbbSelPC.Clear;
   s:=S40pref;
  _msg('Scan phone...');
  _msg('Detected : '+s);
select:
  _msg('Checking product path....');
  if Phoenixfolder<>'' then begin
   if not DirectoryExists(phoenixfolder+'\'+s)  then begin
   _msg('Product not found... Check of right dirrectory..');    // проверяем есть ли такая папка
   _msg(''); setready; Exit; end
   else begin
   _msg('Gathering info...');

      i:=0;
      VplList:=TStringList.Create;
      If FindFirst(phoenixfolder+'\'+s+'\*.vpl', faAnyFile, SearchRec)=0 then
      repeat
      VplList.Add(phoenixfolder+'\'+s+'\'+SearchRec.name);
      i:=i+1;
      until FindNext(SearchRec) <> 0;
      FindClose(SearchRec);
      cou:=i-1;
       if cou=-1 then begin _msg('Not found any any product specific file.. :(');
       SetReady;
       _msg('');
       Exit;
       end;
      for i:=0 to cou do
      begin
      //_msg(FindDescr(VplList.Strings[i]));
      cbbSelPC.Items.Add(FindDescr(VplList.Strings[i]));
      cbbSelPC.ItemIndex:=0;
      end;
      _msg('Select needed configuration and press Ok');
      currproduct:=phoenixfolder+'\'+s+'\';
      VplList.Free;
   end;
  end
  else begin _msg('Select Product path in settings!'); _msg(''); setready; Exit; end;
 end;
 SetReady;
end;

procedure TForm1.RdSmsClick(Sender: TObject);
var
i,Len           :integer;
path,fpath,
tpath           :String;
FL              :TStrings;
i2              :integer;
Ss              :System.Text;
F               :TFileStream;
s               :string;
begin
  {$I VM_Start.inc}
//   {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

  if RdSms.Caption='Stop' then
  begin
  stop:=true;
  exit;
  end;

   SetBuzy;
   RdSms.Caption:='Stop';
   RdSms.Enabled:=True;
   Application.ProcessMessages;

   if Smart then chkPackread.checked:=false;
   Application.ProcessMessages;

   if chkPackread.Checked=True then
   begin
     if Smart=True then
     begin
     SetReady;
     Exit;
     end;
      pb1.Progress:=0;
      with SaveDialog do
      begin
            Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
            +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
            -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
            -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
            FilterIndex:=1;
            FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text);
            InitialDir := '.\';
            DefaultExt := '.smspkg';
             Filter := 'Series40SMS(*.smspkg)|*.smspkg';
            FilterIndex:=1;
            Title:='Save SMS package to ...';
      end;
        if SaveDialog.Execute then
        begin
         if ScanProcess then begin Application.Terminate; exit; end;
         try
          _msg('BackUp UserData : [SMS/MMS]');
         // _msg('Generation mode : [S40]');
          _msg('Selected package method...');
         if not s40drvscan then ReadDataType('SMS Package','C:/PredefMessages/',SaveDialog.FileName)
         else ReadDataType('SMSPackage','S:/PredefMessages/',SaveDialog.FileName)
         except
         _msg('Error when read :( Try again');
         _msg('');
         SetReady;
         Exit;
         end;
         Form1._msg('Done!');
         Form1._msg('');
         SetReady;
         exit;
        end
        else
        begin
         SetReady;
         Exit;
        end;
   end;

   FL:=TStringList.Create;
   if not smart then begin
    _msg('BackUp UserData : [SMS/MMS]');
    _msg('Generation mode : [S40]');
    if not s40drvscan then  path:=Utf8Encode('c:\predefmessages\') else  path:=Utf8Encode('s:\predefmessages\');
   //_msg('List of '+path+' directory');
   _msg('Scanning FileSystem..');
   //_msg(GetUsbDir(path));
    try
    GetS40FileList(FL,path);
    except
    Application.ProcessMessages;
    end;
   _msg('Scan done, processing data...');
   _msg('Total - '+IntToStr(FL.Count)+' files');
   _msg('Reading, wait....');
       pb1.maxvalue:=FL.Count;
       Application.ProcessMessages;
             System.Assign ( Ss , RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\SMS.txt' )) ;
             System.Rewrite ( Ss );

     for i:=0 to FL.Count-1 do begin
     len:=0;
      if stop=True then
      begin
      dostop('READ SMS/MMS');
      Application.ProcessMessages;
      fl.Free;
      form1.pb1.progress:=0;
      form1.pbsm1.progress:=0;
      setready;
      Exit;
      end;
     //Len:=StrToInt(Copy(FL.Strings[i],1,(Pos(':',FL.Strings[i])-1)));
     fpath:=FL.Strings[i];
      //_msg('Reading');
      //_msg(IntToStr(Len));
      //_msg(Utf8Decode(fpath));
      //_msg('');
      tpath:=fpath;
      Delete(fpath,1,3);
      path:='.\'+StatusBar.Panels.Items[2].Text+'\'+Utf8ToAnsi(fpath);
      //_msg(tpath);
      //if not DirectoryExists(ExtractFilePath(path)) then CreateDir(ExtractFilePath(path));
       Len:=s40getsizeuni(tpath);
       if Len>0 then begin
       M:=TmemoryStream.Create;
       s40extractuni(M,tpath,Len,2);
       M.Seek(0,soFromBeginning);
        if M.Size<>0 then begin
         F:=TFileStream.Create(RightFileName(path),fmCreate);
         F.CopyFrom(M,M.Size);
         F.Free;
         try
         S40SMSConv(M);
         if SMSRec.Typ<>'' then begin
         System.Writeln(Ss,'======================================================');
         if SMSRec.Typ ='0' then s:= 'Recived from '+SMSRec.Num else s:='Send to '+SMSRec.Num;
         System.Writeln(Ss,s+'   Date: '+SMSRec.DatTim+ ' Part: '+SMSRec.Part);
         System.Writeln(Ss,Utf8ToAnsi(SMSRec.Bod));
         System.Writeln(Ss,'======================================================');
         System.Writeln(Ss,'');
         end;
          except
          //_msg('Error while convert message! skip...');
           Application.ProcessMessages;
         end;
        end;
        M.Free;
       end;
       pb1.progress:=pb1.progress+1;
       //sleep(200);
     end;
   end else begin
     if Generation='01' then begin
       path:=Utf8Encode('C:\System\Mail\');
       if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text)) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text));
       if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\System')) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\System'));
       end
       else begin
       path:=Utf8Encode('C:\Private\1000484b\Mail2\');
       if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text)) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text));
       if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\Private')) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\Private'));
       if not DirectoryExists(RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\Private\1000484b')) then CreateDir(RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\Private\1000484b'));
       end;
  // _msg('List of '+path+' directory');
  // _msg('');

        _msg('BackUp UserData : [SMS/MMS]');
        _msg('Generation mode : [S60]');
        if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
     _msg('Operating mode is OK, no need change...');
     Application.ProcessMessages;
     end
     else SetMode('Test');

  /// начнем, пожалуй ;)
      prereadstuff;
      Sleep(500);
      Application.ProcessMessages;
    if not startFS60uni then begin
        _msg('FS run fail, please, remove SD card first');
        _msg('Change phone mode manualy to local/test and try again');
        _msg('If still no luck - phone have damaged FS/SD-MMC part..');
        _msg('Done with major error... :(');
        _msg('');
        SetReady;
        Exit;
      end;
      _msg('Fsrun OK...');
      _msg(AperunUni);

   //   _msg(GetUsbDir(path));

      GetS60FileList(FL,path);
   //_msg('');
   _msg('Total - '+IntToStr(FL.Count)+' files');
   Form1.pb1.maxvalue:=FL.Count;
   _msg('Reading, wait....');
       Application.ProcessMessages;
             System.Assign ( Ss , RightFileName('.\'+StatusBar.Panels.Items[2].Text+'\SMS.txt' )) ;
             System.Rewrite ( Ss );



   for i:=0 to FL.Count-1 do begin
    // Len:=StrToInt(Copy(FL.Strings[i],1,(Pos(':',FL.Strings[i])-1)));
     fpath:=FL.Strings[i];
      if stop=True then
      begin
      dostop('READ SMS/MMS');
      Application.ProcessMessages;
      fl.Free;
      form1.pb1.progress:=0;
      form1.pbsm1.progress:=0;
      setready;
      Exit;
      end;
  // _msg('Reading');
  //   _msg(IntToStr(Len));
  // _msg(Utf8Decode(fpath));
   tpath:=fpath;
   Delete(fpath,1,3);
    path:='.\'+StatusBar.Panels.Items[2].Text+'\'+Utf8ToAnsi(fpath);
//   _msg(path);
//    if not DirectoryExists(ExtractFilePath(path)) then CreateDir(ExtractFilePath(path));
//    if ConMode=0 then begin
    Len:=getsizeS60Uni(tpath);
    if Len>0 then begin
    M:=TmemoryStream.Create;
    S60extractuni(M,tpath,Len,2);
    M.Seek(0,soFromBeginning);
      if M.Size<>0 then begin
      F:=TFileStream.Create(RightFileName(path),fmCreate);
      F.CopyFrom(M,M.Size);
      F.Free;
      try
      S60SMSConv(M);
       if SMSRec.Typ<>'' then begin
       System.Writeln(Ss,'======================================================');
       if SMSRec.Typ ='0' then s:= 'Recived from '+SMSRec.Num else s:='Send to '+SMSRec.Num;
       System.Writeln(Ss,s+'   Date: '+SMSRec.DatTim);
       System.Writeln(Ss,SMSRec.Bod);
       System.Writeln(Ss,'======================================================');
       System.Writeln(Ss,'');
       end;
       except
       _msg('Error while convert message! skip...');
       Application.ProcessMessages;
      end;
     end;
     M.Free;
    end
    else begin
    _msg('Error on CS packet! Skipping...');
    end;
//    end;
    pb1.progress:=pb1.progress+1;
   end;
   end;
   System.Close(Ss);
  _msg('Readed data saved to : BEST/IMEI/SMS.txt');
  _msg ('Read Done !');
  _msg ('');
   pb1.MaxValue:=100;
   pb1.Progress:=0;
   FL.Free;
   _msg(SetReady);
  _msg ('');
end;

procedure TForm1.btnWriteRPLClick(Sender: TObject);
var
RS : TStrings;
s  : widestring;
a  : string;
crd: string;
i  : Integer;
xt : integer;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    crd:=CardPass(crpass);
    if crd <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
    {$I VM_End.inc}
  s:='';
 case MessageBox(0, 'WARNING!'+#13+#10+'RPL operations can DESTROY Phone Certificates permanently!'+#13+#10+'Do All Backup before work with RPL Write/Erase!'+#13+#10+''+#13+#10+'ERASE CRT - DESTROY selected Flash certificates!', 'RPL Write/Erase confirm', MB_ICONWARNING or MB_OKCANCEL) of
  idOk: Application.ProcessMessages;
  idCancel: Exit ;
 end;
      setBuzy;
      if ConMode=1 then DisUfsButton;
      if btnWriteRPL.caption='Write RPL'
      then
      begin
      with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := 'rpl';
       Filter := 'rpl files (*.rpl)|*.rpl';
       Title:='Open RPL file ';
      end;
    if OpenDialog.Execute then
    begin
    _msg('Will Write RPL keys now...');
    _msg('Check RPL file...');
    RS:=TStringList.Create;
    RS.LoadFromFile(OpenDialog.FileName);
     if Pos('REBUILD DATA',RS.Strings[0])<>0 then
     begin
     Form1._msg('NMP RPL Detected, converting...');
     DecodeRPL(OpenDialog.FileName,true);
     if FileExists(copy(OpenDialog.FileName,1,Length(OpenDialog.FileName)-4)+'_plain.rpl')=false then
      begin
      Application.ProcessMessages;
      form1._msg('Error convert RPL!!! Check file');
      Form1._msg('Abort writing... :(');
      Form1._msg('');
      Application.ProcessMessages;
      SetReady;
      RS.Free;
      Exit;
      end;
     Application.ProcessMessages;
     RS.Free;
     RS:=TStringList.Create;
     RS.LoadFromFile(copy(OpenDialog.FileName,1,Length(OpenDialog.FileName)-4)+'_plain.rpl');
     Form1._msg('Convert done!');
     Application.ProcessMessages;
     end;
    PlainRplPar(RS);
    if RPLRecord.NPC<>'' then _msg('NPC Data found!') else chkErNPC.checked:=false;
    if RPLRecord.CCC<>'' then _msg('CCC Data found!') else chkErCC.checked:=false;
    if RPLRecord.HWC<>'' then _msg('HWC Data found!') else chkErHWC.checked:=false;
    if RPLRecord.variant<>'' then _msg('Variant Data found!');
    if RPLRecord.SIMLOCK<>'' then _msg('SimLock Data found!') else chkSimlock.checked:=false;
    if RPLRecord.SIMLOCK_KEY<>'' then _msg('SimLock key found!') else chkSimlock.checked:=false;
    if RPLRecord.SUPERDONGLE_KEY<>'' then _msg('SuperDongle Key found!') else chkSD.checked:=false;
    if RPLRecord.CMLA_KEY<>'' then _msg('CMLA key found!') else chkCLMa.checked:=false;
    if RPLRecord.WMDRM_PD<>'' then  _msg('WMDRM key found!') else chkStufCert.checked:=false;
    s:=Copy(RPLRecord.Simlock,41,Length(RPLRecord.Simlock)-40);

     case ConMode of
     0:
      begin
       case PhonePresentmode of
        $00:
        begin
           if not ExtractloaderXSRRap3Gv4(1) then
            begin
             _msg('Looks like ASIC not supported, or HW failure');
             _msg('Supported : RapuYama, RAP3Gv4, BroadComm');
             _msg('Try Flash latest SW and repeat, if phone in supported list');
             _msg('');
             setready;
             if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
             Exit;
            end;

            fltime:=0;
            Form1._msg('Reopening the connection...');
            Application.ProcessMessages;
             Sleep(500);
            Application.ProcessMessages;

            i:=30;
            while i>0 do
            begin
            Form1._msg('Waiting for response: '+inttostr(i));
            Application.ProcessMessages;
            if catchdevice<>$02 then
            begin
            Application.ProcessMessages;
            sleep (1000);
            Application.ProcessMessages;
            end
            else i:=0;
            dec(i);
            end;

            if not DevPresent then
            begin
            Form1._msg('Phone not found... :(');
            Form1._msg('');
            Form1.StatusBar.Panels[4].Text:='';
            SetReady;
            USBClosePort;
            if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
            exit;
            end;

            RAPnewChkADLWCRT;

            Form1._msg('ADL: Preparing for write certificates...');
            Form1._msg('');
           if (chkErNPC.Checked=true) and (RPLRecord.NPC<>'') then
           begin
           if CertErase('NPC') then form1._msg('Erase NPC... Ok');
           if buildxsr16cert(RPLRecord.NPC,'NPC') then _msg('Writing NPC... Ok');
           end;
           if (chkErCC.checked=True) and (RPLRecord.CCC<>'') then
           begin
           if CertErase('CCC') then form1._msg('Erase CCC... Ok');
           if buildxsr16cert(RPLRecord.CCC,'CCC') then _msg('Writing CCC... Ok');
           end;
           if (chkerHWC.Checked=true) and (RPLRecord.HWC<>'') then
           begin
           if CertErase('HWC') then form1._msg('Erase HWC... Ok');
           if buildxsr16cert(RPLRecord.HWC,'HWC') then _msg('Writing HWC... Ok');
           end;
            Form1._msg('');
            Form1._msg('ADL: Writing Flash certs done! :)');
            _msg('');
            RapNewFinish;

            if (chkSimlock.Checked=false) and (chkSD.Checked=false) and (chkStufCert.Checked=false)then
            begin
            form1._msg('');
            Form1._msg('-> No any Flex keys selected, skip flex part');
            form1._msg('');
            pb1.Progress:=0;
            //disconnectfill;
                _msg('Done!');
                _msg('');
                if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
                SetReady;
            Exit;
            end;

            Form1._msg('Wait, reconneting...');
            Application.ProcessMessages;
            //Sleep(1000);
            //Application.ProcessMessages;
            i:=1200;
            while i>0 do
            begin
            //Form1._msg('Waiting for response: '+inttostr(i));
            Application.ProcessMessages;
             if catchdevice<>$01 then
             begin
             Application.ProcessMessages;
             sleep (100);
             Application.ProcessMessages;
             Form1.StatusBar.Panels[1].Text:=IntToStr(i);
             end
             else i:=0;
             dec(i);
            end;
            if not DevPresent then
            begin
            Form1._msg('Phone not found... :(');
            Form1._msg('CertWrite failed : phone was not bootup');
            Form1._msg('Connection/SW/HW problem, try bootup manually');
            Form1._msg('If phone bootup Ok - write only flex keys');
            Form1._msg('');
            Form1.StatusBar.Panels[4].Text:='';
            SetReady;
            if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
            USBClosePort;
            exit;
            end;
        end;
        $01:
        begin
        _msg('-> Skip Flash keys Part, for Flash Part use Dead Mode or Fbus');
        Application.ProcessMessages;
        end;
       end;
      end;
     1:
      begin
        case fbdev of
         1:
         begin
             if ((chkerNPC.checked=true) and (RPLRecord.NPC<>'')) or ((chkerCc.checked=True) and (RPLRecord.CCC<>'')) or ((chkerHWC.checked=true) and (RPLRecord.HWC<>''))
             then
             begin
                BUsCheckCMTonly;
                if boot_done=True
                then
                begin
                 Form1._msg('Preparing for write certificates...');
                 Form1._msg('');
                 if (chkErNPC.checked=True) and (RPLRecord.NPC<>'') then begin
                 if UFSeraseCRT('NPC',$00) then form1._msg('Erase NPC... Ok');
                 if buildUFScert(RPLRecord.NPC,'NPC',$00) then _msg('Writing NPC... Ok');
                 Form1._msg('');
                 Application.ProcessMEssages;
                 end;
                 if (chkErCC.checked=true) and (RPLRecord.CCC<>'') then
                 begin
                 if UFSeraseCRT('CCC',$00) then form1._msg('Erase CCC... Ok');
                 if buildUFScert(RPLRecord.CCC,'CCC',$00) then _msg('Writing CCC... Ok');
                 Form1._msg('');
                 Application.ProcessMEssages;
                 end;
                 if (chkerHWC.Checked=true) and (RPLRecord.HWC<>'') then
                 begin
                 if UFSeraseCRT('HWC',$00) then form1._msg('Erase HWC... Ok');
                 if buildUFScert(RPLRecord.HWC,'HWC',$00) then _msg('Writing HWC... Ok');
                 Form1._msg('');
                 Application.ProcessMEssages;
                 end;

                 if RPLRecord.variant<>'' then
                 begin
                 if UFSeraseCRT('VARIANT',$00) then form1._msg('Erase VARIANT... Ok');
                 if buildUFScert(RPLRecord.Variant,'VARIANT',$00) then _msg('Writing VARIANT... Ok');
                 Form1._msg('');
                 Application.ProcessMEssages;
                 end;
                  
               end
               else
               begin
               form1._msg('Boot failed! :(');
               Form1._msg('If phone RAPUYAMA, RAP3Gv4 or BroadComm - Use USB cable ;)');
               form1._msg('');
               end;
             end
             else
             begin
              if (RPLRecord.npc='') and (RPLRecord.ccc='') and (RPLRecord.hwc='') then form1._msg('No any FLASH keys detected, Skip FLASH part')
              else form1._msg('No any FLASH keys selected, Skip FLASH part');
             end;

         end;
         0: Application.ProcessMessages;
       end;
      end;
     end;
    //_msg(s);
     if (chkSimlock.Checked=True) or (chkSD.Checked=True)  or (chkStufCert.Checked=True) or (chkCLMA.checked=true)  then
     begin
        if (ConMode=1) and (fbdev=1) then
        begin
         if ReadPhMode<>'Error' then Application.ProcessMessages
         else
         begin
          if InitServiceMode then Application.ProcessMessages
          else
          begin
          Form1._msg('Service mode init failed! :(');
          Form1._msg('Check Cable/BSI/HW, try again');
          Form1._msg('');
          disconnectfill;
          SetReady;
          Exit;
          end;
         end;
        end;
        
      SetMode('Test');

      xt:=0;
      repeat
      Application.ProcessMessages;
      Inc(xt);
      sleep(20)
      until (ReadPhMode<>'Error') or (xt=20);

      if xt=20 then
      begin
      _msg('Failed init Test mode... :(');
      _msg('');
      SetReady;
      exit;
      end;

      ReadPhoneInfo;

      _msg('');
       if chkSimlock.Checked=true then
       begin
        if Length(RPLRecord.SimLock_key)=200 then
       begin
         if RPLRecord.SimLock_key<>'' then
        begin
          case ConMode of
          1:
          begin
          if RPLRecord.Simlock<>'' then
           if WriteSLDataSL2(s) then Form1._msg('Writing SimLock Data...   Ok') else Form1._msg('Writing SimLock Data...   Error');
          Application.ProcessMessages;
          if RPLRecord.SIMLOCK_KEY<>'' then
           if WriteSLkeySL2(RPLRecord.SimLock_key) then Form1._msg('Writing SimLock Key...   Ok') else Form1._msg('Writing SimLock Key...   Error');
          end;
          0:
          begin
          if RPLRecord.Simlock<>'' then _msg('Writing SimLock Data...   '+UsbRplsimlockdata(s));
          if RPLRecord.SIMLOCK_KEY<>'' then  _msg('Writing SimLock Key...   '+UsbWriteSimLokkey(RPLRecord.SimLock_key));
          end;
         end;
        end;
       end
       else
       begin
        if Length(RPLRecord.SimLock_key)>300 then
        begin
        if (RPLRecord.SimLock_key<>'') and (RPLRecord.Simlock<>'') then
        begin
         if CreateSimLockRpl(RPLRecord.SimLock_key,s) then
         begin
         _msg('Writing SimLock Key...   Ok!');
         _msg('Writing SimLock Data...  Ok!');
         end
         else
         begin
         _msg('Writing SimLock Key...   Error!');
         _msg('Writing SimLock Data...  Error!');
         end;
        end
        else _msg('Data inside RPL is damaged or not full, impossible write SimLock keys');
        end
        else  _msg('Data inside RPL is damaged or not full, impossible write SimLock keys');
       end;
      end;
      if chkSD.Checked=True then if RPLRecord.SUPERDONGLE_KEY<>'' then
      begin
        case conmode of
         0: _msg('Writing Super Dongle Key...   '+UsbWriteSDDkey(RPLRecord.SUPERDONGLE_KEY));
         1: if FWriteSDkeySLx(RPLRecord.SUPERDONGLE_KEY) then Form1._msg('Writing Super Dongle Key...   Ok') else Form1._msg('Writing Super Dongle Key...   Error');
        end;
      end;
      RS.Free;
      _msg('');
      if not ReadPhoneInfoAll then Form1._msg('Error read initial info :(');
      if conmode=1 then FbusSendSynk;
      _msg('SDD Key status : '+checkSD);
      Application.ProcessMessages;
      sleep(50);
       xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('21');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=3);

      if a='PASSED' then Form1._msg('SimLock status : SimLock is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('SimLock status : Can'+#39+'t get status ') else Form1._msg('SimLock status : SimLock Damaged!!!!! :('); end;
      Application.ProcessMessages;
       sleep(50);
      a:='';
      xt:=0;
      repeat
      Fbussendsynk;
      Sleep(100);
      Application.ProcessMessages;
      a:=testitemst('5D');
      inc(xt);
      until (a='PASSED') or
            (a='-> ERROR') or
            (a='NOT EXECUTED')or
            (a='NOT RUN') or
             (xt=3);

      if a='PASSED' then Form1._msg('Security status : Security is Ok') else begin if (a='NOT EXECUTED') or (a='NOT RUN') then Form1._msg('Security status : Can'+#39+'t get status ') else Form1._msg('Security status : Security Damaged!!!!! :(') end;
      a:='';
      Application.ProcessMessages;

     _msg('');


       // Write CLMA key
      if (chkCLMA.checked=true) and (RPLRecord.CMLA_KEY<>'')  then
      begin
       case conmode of
       0 : if UsbWriteCLMA(RPLRecord.CMLA_KEY) then Form1._msg('CMLA key sent... Ok') else Form1._msg('Write CMLA... Error');
       1: Application.ProcessMessages;
       end;
      end;

      // Write WDRM_PD key
      if (chkStufCert.checked=true) and (RPLRecord.WMDRM_PD<>'') then
       begin
         case ConMode of
         0: if writeWDRM_PD(RPLRecord.WMDRM_PD) then Form1._msg('WMDRM_PD key sent... Ok') else Form1._msg('Write WMDRM_PD... Error');
         1: Application.ProcessMessages;
         end;
       end;
     end;
    _msg('');
    _msg('Done!');
    _msg('');
    end;

  end
  else
  begin
   case ConMode of
    1:   // UFS
    begin
     if fbdev=0 then Exit;
          begin
              if (chkErNPC.Checked=True) or (chkerHWC.Checked=True) or chkErCC.Checked=true then
              begin
                BUsCheckCMTonly;
                if boot_done=True
                then
                begin
                 Form1._msg('Erasing selected certificates...');
                 Form1._msg('');
                 if  chkErNPC.checked=True then begin
                 if UFSeraseCRT('NPC',$00) then form1._msg('Erase NPC... Ok');
                 Application.ProcessMEssages;
                 end;
                 if  chkErCC.checked=true  then
                 begin
                 if UFSeraseCRT('CCC',$00) then form1._msg('Erase CCC... Ok');
                 Application.ProcessMEssages;
                 end;
                 if  chkerHWC.Checked=true then
                 begin
                 if UFSeraseCRT('HWC',$00) then form1._msg('Erase HWC... Ok');
                 Application.ProcessMEssages;
                 end;
                 Form1._msg('');
                 Form1._msg('Cert erased ok');
                 Form1._msg('');
                 disconnectfill;
                 SetReady;
                 Exit;
                end;

              end
              else
              begin
              SetReady;
              exit;
              end;
          end;
    end;
    0:  //USB, will be for Rapu, V4, BroadComm
    begin
          case PhonePresentmode of
         $00:
        begin
           if not ExtractloaderXSRRap3Gv4(1) then
            begin
             _msg('Looks like ASIC not supported, or HW failure');
             _msg('Supported : RapuYama, RAP3Gv4, BroadComm');
             _msg('Try Flash latest SW and repeat, if phone in supported list');
             _msg('');
             if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
             setready;
             Exit;
            end;

            fltime:=0;
            Form1._msg('Reopening the connection...');
            Application.ProcessMessages;
             Sleep(500);
            Application.ProcessMessages;

            i:=30;
            while i>0 do
            begin
            Form1._msg('Waiting for response: '+inttostr(i));
            Application.ProcessMessages;
            if catchdevice<>$02 then
            begin
            Application.ProcessMessages;
            sleep (1000);
            Application.ProcessMessages;
            end
            else i:=0;
            dec(i);
            end;

            if not DevPresent then
            begin
            Form1._msg('Phone not found... :(');
            Form1._msg('');
            Form1.StatusBar.Panels[4].Text:='';
            SetReady;
            USBClosePort;
            if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
            exit;
            end;

            RAPnewChkADLWCRT;
           Application.ProcessMessages;
            Form1._msg('ADL: Preparing for erase certificates...');
            Form1._msg('');
           Application.ProcessMessages;
           if chkErNPC.Checked=true then
           if CertErase('NPC') then form1._msg('Erase NPC... Ok');
           Application.ProcessMessages;
           if chkErCC.checked=True then
           if CertErase('CCC') then form1._msg('Erase CCC... Ok');
           Application.ProcessMessages;
           if chkerHWC.Checked=true then
           if CertErase('HWC') then form1._msg('Erase HWC... Ok');
           Application.ProcessMessages;
            Form1._msg('');
            Form1._msg('ADL: Erase Flash certs done! :)');
            _msg('');
            RapNewFinish;
            pb1.Progress:=0;
            //disconnectfill;
            _msg('Done!');
            _msg('');
            SetReady;
            if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
            Exit;

        end;
        $01 :
        begin
        _msg('-> Cert Earse can be done only in DEAD mode, Check DEAD mode, and connect powered OFF phone');
        Application.ProcessMessages;
        _msg('');
        SetReady;
        if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
        Exit;
        end;
       end;
    end;

    end;

 end;
    pb1.Progress:=0;
    if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
    disconnectfill;
    SetReady;
end;

procedure TForm1.ModelselChange(Sender: TObject);
begin
  cbbModeFlash.ItemIndex:=0;
      if Usini.Checked then begin  Usini.Checked:=false; Usini.Checked:=true; end;
end;

procedure TForm1.cnt3bClick(Sender: TObject);
begin
       with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       if DirectoryExists (phoenixfolder+Modelsel.Text+'\') then InitialDir := phoenixfolder+Modelsel.Text+'\' else InitialDir := phoenixfolder;
        Filter := 'CNT files (*.image)|*.image*;|CNT files (*.fpsx)|*.fpsx*;|All file(*.*)|*.*';
       Title:='Select CNT file';
      end;
    if OpenDialog.Execute then begin
       CNT3t.Text:= ExtractFilename(OpenDialog.FileName);
       chkCNT3.Checked:=true;
       cnt3:=OpenDialog.FileName;
    end else begin CNT3t.Text:='';chkCNT3.Checked:=false; cnt3:=''; end;
end;

procedure TForm1.cntbClick(Sender: TObject);
begin
       with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       if DirectoryExists (phoenixfolder+Modelsel.Text+'\') then InitialDir := phoenixfolder+Modelsel.Text+'\' else InitialDir := phoenixfolder;
        Filter := 'CNT files (*.image)|*.image*;|CNT files (*.fpsx)|*.fpsx*;|All file(*.*)|*.*';
       Title:='Select CNT file';
      end;
    if OpenDialog.Execute then begin
       CNTt.Text:= ExtractFilename(OpenDialog.FileName);
       chkCNTe.Checked:=true;
       image:=OpenDialog.FileName;
    end else begin CNTt.Text:='';chkCNTe.Checked:=false; image:=''; end;
end;

procedure TForm1.apebClick(Sender: TObject);
begin
       with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       if DirectoryExists (phoenixfolder+Modelsel.Text+'\') then InitialDir := phoenixfolder+Modelsel.Text+'\' else InitialDir := phoenixfolder;
        Filter := 'APE files (*.fpsx)|*.fpsx*;|All file(*.*)|*.*';
       Title:='Select APE file';
      end;
    if OpenDialog.Execute then begin
       APEt.Text:= ExtractFilename(OpenDialog.FileName);
       chkAPEe.Checked:=true;
       ape:=OpenDialog.FileName;
       end else begin APEt.Text:='';chkAPEe.Checked:=false; ape:=''; end;
end;

procedure TForm1.SelectFiles();
var
i:integer;
s:string;
userini:TIniFile;
langlist : TStringList;
b : boolean;
begin
       MCUt.Text:= '';
       PPMt.Text:= '';
       PPM1t.Text:= '';
       CNTt.Text:= '';
       APEt.Text:= '';
       CNT3t.Text:='';
       core:='';
       ppm:='';
       ppmselect:=false;
       ppm1:='';
       ppm1select:=false;
       ppmlang:='';
       ppm1lang:='';
       image:='';
       ape:='';
       cnt3:='';
       swver:='';
       PPMt.Hint:='';
       chkMCUen.Checked:=false;
       chkPPMe.Checked:=false;
       chkCNTe.Checked:=false;
       chkCNT3.Checked:=false;
       chkAPEe.Checked:=false;
     if usini.Checked then begin
       if VplList.Count=0 then exit;
       if not FindNam(VplList.Strings[cbbSelPC.ItemIndex]) then exit;
       if core <> '' then begin
        MCUt.Text:=core;
        chkMCUen.Checked:=true;
        core:=phoenixfolder+Modelsel.text+'\'+MCUt.Text;
       end;
       PPMt.Text:=ppm;
       if PPMt.Text <> '' then
       begin
        chkPPMe.Checked:=true;
        ppm:=phoenixfolder+Modelsel.text+'\'+PPMt.Text;
        if (ppm<>'')   and (chkPPMe.Checked=True) then
         begin
          if Not ppmselect then
          begin
               LangList:=TStringList.Create;
               b:=false;
               GetPPMLanguage(ppm, LangList, b);
               if b then
               begin
                    i:=0; ppmlang:='';
                    while i<LangList.Count do
                    begin
                         ppmlang:=ppmlang+LangList.Strings[i];
                         inc(i);
                         if i<>LangList.Count then ppmlang:=ppmlang+', ';
                    end;
                    if ppmlang<>'' then
                    begin
                         ppmselect:=true;
                         PPMt.Hint:=ppmlang;
                    end
                    else  PPMt.Hint:='';
               end;
               LangList.Free;
          end
          else if ppmlang<>'' then PPMt.Hint:=ppmlang else PPMt.Hint:='';
         end;
       end;
       PPM1t.Text:=ppm1;
       if PPM1t.Text <> '' then begin
        chkPPM1e.Checked:=true;
        ppm1:=phoenixfolder+Modelsel.text+'\'+PPM1t.Text;
       end;
       CNTt.Text:=image;
       if  CNTt.Text<> '' then begin
         chkCNTe.Checked:=true;
         image:=phoenixfolder+Modelsel.text+'\'+CNTt.Text;
       end;
       APEt.Text:=ape;
       if  APEt.Text<> '' then begin
          chkAPEe.Checked:=true;
          ape:=phoenixfolder+Modelsel.text+'\'+APEt.Text;
       end;
       CNT3t.Text:=cnt3;
       if  CNT3t.Text<> '' then begin
          chkCNT3.Checked:=true;
          cnt3:=phoenixfolder+Modelsel.text+'\'+CNT3t.Text;
       end;
     end else begin
       userini:=TIniFile.Create(StartDir+'userini.ini');
        core:=userini.ReadString(cbbselpc.Items.Strings[cbbselpc.ItemIndex],'1','');
        if core<>'' then begin
        MCUt.Text:=ExtractFilename(core);
        chkMCUen.Checked:=true;
        end;
        ppm:=userini.ReadString(cbbselpc.Items.Strings[cbbselpc.ItemIndex],'2','');
        if ppm<>'' then begin
        PPMt.Text:=ExtractFilename(ppm);
        chkPPMe.Checked:=true;
        end;
        ppm1:=userini.ReadString(cbbselpc.Items.Strings[cbbselpc.ItemIndex],'3','');
        if ppm1<>'' then begin
        PPM1t.Text:=ExtractFilename(ppm1);
        chkPPM1e.Checked:=true;
        end;
        image:=userini.ReadString(cbbselpc.Items.Strings[cbbselpc.ItemIndex],'4','');
        if image<>'' then begin
        CNTt.Text:=ExtractFilename(image);
        chkCNTe.Checked:=true;
        end;
        ape:=userini.ReadString(cbbselpc.Items.Strings[cbbselpc.ItemIndex],'5','');
        if ape<>'' then begin
        APEt.Text:=ExtractFilename(ape);
        chkAPEe.Checked:=true;
        end;
        cnt3:=userini.ReadString(cbbselpc.Items.Strings[cbbselpc.ItemIndex],'6','');
        if cnt3<>'' then begin
        CNT3t.Text:=ExtractFilename(cnt3);
        chkCNT3.Checked:=true;
        end;
       userini.Free;
     end;
end;

procedure TForm1.SearchVpl();
var
i,cou:integer;
SearchRec:TSearchRec;
begin
     i:=0;
     VplList.Clear;
     If FindFirst(phoenixfolder+Modelsel.Text+'\*.vpl', faAnyFile, SearchRec)=0 then
      repeat
      VplList.Add(phoenixfolder+Modelsel.Text+'\'+SearchRec.name);
      i:=i+1;
      until FindNext(SearchRec) <> 0;
      FindClose(SearchRec);
      cou:=i-1;
       if cou=-1 then exit;
       cbbSelPC.Clear;
       for i:=0 to cou do cbbSelPC.Items.Add( FindDescr(VplList.Strings[i]));
       cbbSelPC.Enabled:=true;
       cbbSelPC.ItemIndex:=0;
       if StatusBar.Panels.Items[3].Text = 'Disconnected' then cbbSelPC.ItemIndex:=0
       else for i:=0 to cou do if Pos(PhInfoRecord.ProductCode,cbbSelPC.Items.Strings[i])<>0 then cbbSelPC.ItemIndex:=i;
       SelectFiles;
end;

procedure TForm1.UsIniClick(Sender: TObject);
begin
     if Usini.Checked then begin
     userin.Checked:=false;
     if StatusBar.Panels.Items[3].Text = 'Connected' then Modelsel.Text:=RM;
     SearchVpl;
     if VplList.Count<>0 then cbbSelPC.Enabled:=true;
     end else begin
       MCUt.Text:= '';
       PPMt.Text:= '';
       PPM1t.Text:= '';
       CNTt.Text:= '';
       APEt.Text:= '';
       CNT3t.Text:='';
       chkMCUen.Checked:=false;
       chkPPMe.Checked:=false;
       chkPPM1e.Checked:=false;
       chkCNTe.Checked:=false;
       chkAPEe.Checked:=false;
       chkCNT3.Checked:=false;
       core:='';
       ppm:='';
       ppmselect:=false;
       ppm1:='';
       ppm1select:=false;
       ppmlang:='';
       ppm1lang:='';
       image:='';
       ape:='';
       cnt3:='';
       swver:='';
       VplList.Clear;
       cbbSelPC.Clear;
       cbbSelPC.Enabled:=false;
//       FlMan.Checked:=true;
    end;
end;

procedure TForm1.mcubClick(Sender: TObject);
begin
       with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       if DirectoryExists (phoenixfolder+Modelsel.Text+'\') then InitialDir := phoenixfolder+Modelsel.Text+'\' else InitialDir := phoenixfolder;
       DefaultExt := 'mcusw';
          Filter := 'Core files (*.mcusw)|*.mcusw*;|Core files (*.fpsx)|*.fpsx*;|All files (*.*)|*.*';
       Title:='Select MCU file';
      end;
    if OpenDialog.Execute then begin
       MCUt.Text:= ExtractFilename(OpenDialog.FileName);
       core:=OpenDialog.FileName;
     chkMCUen.Checked:=true;
    end else begin MCUt.Text:= ''; chkMCUen.Checked:=false; core:=''; end;
end;

procedure TForm1.ppmbClick(Sender: TObject);
var
     i                   : Integer;
     LangList            : TStringList;
begin
     OpenPPMDialog := TOpenPPMDialog.Create(self);
     with OpenPPMDialog do
     begin
          Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
          +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
          -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
          -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
          FilterIndex:=1;
          FileName :='';
          if DirectoryExists (phoenixfolder+Modelsel.Text+'\') then
          InitialDir := phoenixfolder+Modelsel.Text+'\'        else
          InitialDir := phoenixfolder;

          Filter := 'PPM files (*.ppm)|*.ppm*;|PPM files (*.fpsx)|*.fpsx*;|All file(*.*)|*.*';
          Title:='Select PPM file';
     end;

     if OpenPPMDialog.Execute then
     begin
          PPMt.Text:= ExtractFilename(OpenPPMDialog.FileName);
          chkPPMe.Checked:=true;
          ppm:=OpenPPMDialog.FileName;
          LangList:=TStringList.Create;
          LangList:=OpenPPMDialog.LanguageList;
          i:=0; ppmlang:='';
          while i<LangList.Count do
          begin
               ppmlang:=ppmlang+LangList.Strings[i];
               inc(i);
               if i<>LangList.Count then ppmlang:=ppmlang+', ';
          end;
          if ppmlang<>'' then begin
          ppmselect:=true;
          ppmt.Hint:=ppmlang;
          end else PPMt.Hint:='';
          LangList.Free;
     end
     else
     begin
          PPMt.Text:='';
          chkPPMe.Checked:=false;
          ppm:='';
          PPMt.Hint:='';
     end;
     OpenPPMDialog.Free;
end;

procedure TForm1.ppm1bClick(Sender: TObject);
var
     i                   : Integer;
     LangList            : TStringList;
begin
     OpenPPMDialog := TOpenPPMDialog.Create(self);
     with OpenPPMDialog do
     begin
          Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
          +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
          -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
          -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
          FilterIndex:=1;
          FileName :='';
          if DirectoryExists (phoenixfolder+Modelsel.Text+'\') then
          InitialDir := phoenixfolder+Modelsel.Text+'\'        else
          InitialDir := phoenixfolder;

          Filter := 'PPM files (*.ppm)|*.ppm*;|PPM files (*.fpsx)|*.fpsx*;|All file(*.*)|*.*';
          Title:='Select PPM2 file';
     end;

     if OpenPPMDialog.Execute then
     begin
          PPM1t.Text:= ExtractFilename(OpenPPMDialog.FileName);
          chkPPM1e.Checked:=true;
          ppm1:=OpenPPMDialog.FileName;
          LangList:=TStringList.Create;
          LangList:=OpenPPMDialog.LanguageList;
          i:=0; ppm1lang:='';
          while i<LangList.Count do
          begin
               ppm1lang:=ppm1lang+LangList.Strings[i]+', ';
               inc(i);
          end;
          if ppm1lang<>'' then begin
          ppm1select:=true;
          PPM1t.Hint:=ppm1lang;
          end else PPM1t.Hint:='';
          LangList.Free;
     end
     else
     begin
          PPM1t.Text:='';
          chkPPM1e.Checked:=false;
          ppm1:='';
          PPM1t.Hint:='';
     end;
     OpenPPMDialog.Free;
end;

procedure TForm1.FlManClick(Sender: TObject);
begin
     if FlMan.Checked then begin
      userin.Checked:=false;
      mcub.Enabled:=true;
      ppmb.Enabled:=true;
      ppm1b.Enabled:=true;
      cntb.Enabled:=true;
      apeb.Enabled:=true;
      cnt3b.Enabled:=true;
     end else begin
      mcub.Enabled:=false;
      ppmb.Enabled:=false;
      ppm1b.Enabled:=false;
      cntb.Enabled:=false;
      apeb.Enabled:=false;
      cnt3b.Enabled:=false;
      Usini.Checked:=false;
      Usini.Checked:=true;
     end;
end;

procedure TForm1.cbbSelPCChange(Sender: TObject);
begin
       SelectFiles;
end;

function TForm1.PrdCh(Dir:string):string;
begin
if SelectDirectory('Select DataPackage directory','',Dir) then Result:=Dir+'\' else Result:=Dir;
end;

procedure TForm1.WD2ExtractPhoneBook();
var
  datalen,i:Integer;
  a,s1,s:string;
  F:tfilestream;
begin
  with SaveDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :=StatusBar.Panels.Items[0].Text+'_'+StatusBar.Panels.Items[2].Text ;
       InitialDir := '.\';
       DefaultExt := '.WD2pb';
       Filter := 'WD2pb(*.WD2pb)|*.WD2pb';
       Title:='Save WD2phonebook to ...';
       end;
 if SaveDialog.Execute then begin
  setbuzy;
  _msg('Searching for phonebook...');
  _msg('Initialising FS...');
  _msg('Skip check FS...');
  _msg('Use direct acces mode, skip search');
  if ScanProcess then begin Application.Terminate; exit; end;
            _msg('Initialise Reading...');
            FbusSendSynk;
            Application.ProcessMessages;
                   s1:=tphpach+'VCF\';
                   CreateDir(s1);
     s:=ChangeFileExt(SaveDialog.FileName,'.csv');
            M:=TmemoryStream.Create;
          if not fbusgetfileWd2nd(M,'C:\system\DataContacts.cdb',datalen) then begin
          _msg('Error');
       i:=SmartExtract(M,s1,s);
       if i<>0 then begin
       _msg(IntToStr(i)+' vcf files saved to '+s1);
          F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
          EncryptF(M,F,fullid);
          _msg('Saved to '+savedialog.filename);
          F.Free;
          end;
            //M.Seek(0,soFromBeginning);
            //f.CopyFrom(M, m.size);
          M.Free;
          _msg('');
          end
          else begin
       i:=SmartExtract(M,s1,s);
       if i<>0 then begin
       _msg(IntToStr(i)+' vcf files saved to '+s1);
            F:=TFileStream.Create(SaveDialog.FileName,fmCreate);
            EncryptF(M,F,fullid);
           _msg('Saved to '+savedialog.filename);
            F.Free;
            end;
           _msg('Done!');
            //M.Seek(0,soFromBeginning);
            //f.CopyFrom(M, m.size);
            M.Free;
           end;
  _msg(SetReady);
  _msg('');
 end ;
 end;

 ///WD2RepairPhoneBook
procedure TForm1.WD2RepairPhoneBook();
var
  datalen:Integer;
  a:string;
  F:tfilestream;
begin
      with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := '.WD2pb';
       Filter := 'WD2pb(*.WD2pb)|*.WD2pb';
       Title:='Open WD2phonebook...';
      end;
  if OpenDialog.Execute then begin
   setbuzy;
   _msg('Starting PhoneBook repair');
   _msg('Initialising FS...');
   _msg('Skip check FS...');
   _msg('Clear data...');
   FbusSendSynk;
   if ScanProcess then begin Application.Terminate; exit; end;
   Application.ProcessMessages;
   if not FbusDelPhoneBookwd2 then begin
   _msg('Error while prepare! Reconnect&repower phone');
   _msg('');
   setready;
   Exit;
   end;
   Application.ProcessMessages;
    if ScanProcess then begin Application.Terminate; exit; end;
     M:=TmemoryStream.Create;
     F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
     //M.LoadFromStream(F);
     DecryptF(F,M,fullid);
     F.Free;
     M.Seek(0,soFromBeginning);
     FbusSendSynk;
     Application.ProcessMessages;
    if not fbuswritefilewd2(m,'C:\System\DataContacts.cdb') then begin
    _msg('Error while writing! Reconnect&repower phone');
    _msg('');
    SetReady;
    end
    else _msg('Write done!');
     pb1.progress:=0;
     pb1.maxvalue:=100;
     m.Free;
     _msg('Done!');
     _msg(SetReady);
     _msg('');
  end;
 end;

procedure TForm1.chkDEADMODEClick(Sender: TObject);
begin
    if ConMode=0 then begin
     if chkDEADMODE.Checked=true then
     begin
          Setbuzy;
          btnFLASH.Enabled:=True;
          //chkBackup.Enabled:=false;
          chkDOWNGRADE.Enabled:=false;
          //btnReadRPL.enabled:=True;
          //btnWriteRPL.Enabled:=True;
          //btnFormatS40LowLevel.enabled:=True;
          Form1.StatusBar.Panels.Items[6].Text :='DEAD';
     end else
     begin
          SetReady;
          Form1.StatusBar.Panels.Items[6].Text :='READY';
     end;
     end;
end;

procedure TForm1.btnKeyBTestClick(Sender: TObject);
var
sec:string;
begin
       {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

SetBuzy;
 if  btnKeyBtest.Caption='KeyB Test' then begin
_msg('Starting KeyBoard Test procedure...');
 Application.ProcessMessages;
 SetMode('Test');
_msg('Checking Keyboard Stuck : TEST '+testitemst('07'));
  if ConMode=0 then begin
  if not Smart then KBstest else s60startkeybtest;
  end
  else begin
   if not Smart then FKBstest else F60startkeybtest;
  end;
_msg('Phone ready!');
_msg('Now press need keys on phone...');
_msg('For finish test - press "End Test"');
 btnKeyBtest.Caption:='End Test';
 btnKeyBtest.Enabled:=True;
 end
 else begin
   if ConMode=0 then begin
       if not Smart then begin getkeyboardstatus; KBtestEnd;  end
       else begin  checkkeys60; finkeybtests60; end;
   end

   else begin
      if not Smart then begin s40getKbstatus; FKBtestEnd; end
      else begin FBcheckkeys60; FBfinkeybtests60 end;
   end;
 btnKeyBtest.Caption:='KeyB Test';
 _msg('Done!');
 _msg('');
 SetReady;
 end;
end;

procedure TForm1.btnFunLabelClick(Sender: TObject);
var
  s,dta,sec :string;
begin
     {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

   with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := '.s4lbl';
        Filter := 'S40 label (*.s4lbl)|*.s4lbl';
       Title:='Open S40 Label file...';
      end;
    if OpenDialog.Execute then
    begin
      s:=''; dta:='';
    SetBuzy;
    _msg('S40 Label change (*#0010#) started...');
    _msg('Check data...');
    if ScanProcess then begin Application.Terminate; exit; end;
     s:=S40checklbl;
      if s<>'' then begin
      _msg('Reading data...');
      _msg('Resetting <crash>...');
       changerigts($0020,s);
       if not s40delfileuni(s) then
         begin
         _msg('Error while prepare! Restart phone and try again...');
         SetReady;
         _msg('');
         Exit;
         end;
       end;
       s:=S40checklbl;
      if s<>'' then begin
       changerigts($0020,s);
       if not s40delfileuni(s) then
         begin
         _msg('Error while prepare! Restart phone and try again...');
         SetReady;
         _msg('');
         Exit;
         end;
       end;
    _msg('Writing data...');
     if not s40drvscan then dta:='c:\predefgallery\User Content Package BEST' else dta:='c:\User Content Package BEST';
    M:=TmemoryStream.Create;
    M.LoadFromFile(OpenDialog.FileName);
    if not S40WriteUni(M,dta,3) then
      begin
      _msg('Error while prepare! Restart phone and try again...');
      SetReady;
      m.Free;
      _msg('');
      Exit;
      end;
    m.Free;
    _msg('Initialize <crash>...');
    changerigts($0067,dta);
    _msg('Done!');
    _msg('');
    SetReady;
    end;
end;


procedure TForm1.s40smsClick(Sender: TObject);
var
F:TfileStream;
s:string;
begin
   with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := 'D:\Project_Pro\BEST\Best_rel\predefmessages_bug\predefmessages\1\';
       DefaultExt := '*.*';
        Filter := 'S40 sms (*.*)|*.*';
       Title:='Open S40 sms file...';
      end;
    if OpenDialog.Execute then
    begin
          M:=TmemoryStream.Create;
            F:=TFileStream.Create(OpenDialog.FileName,fmOpenRead);
          M.LoadFromStream(F);
          F.Free;
          S40SMSConv(M);
     if SMSRec.Typ<>'' then begin
       _msg('======================================================');
       if SMSRec.Typ ='0' then s:= 'Recived from '+SMSRec.Num else s:='Send to '+SMSRec.Num;
       _msg(s+'   Date: '+SMSRec.DatTim+ ' Part: '+SMSRec.Part);
       _msg(Utf8ToAnsi(SMSRec.Bod));
       _msg('======================================================');
       _msg('');
     end;
          M.Free;
    end;
end;

procedure TForm1.S60flash;
var
  cs        :Byte;
  i         :integer;
  b         :Boolean;
  batval    :integer;
begin
  case chkDEADMODE.Checked of
  false:
   begin
          if chkBackup.checked=true then
          begin
               _msg('Backup CRT308 data...');
               _msg(CRT308backup);
                case chksl of
               1:Application.ProcessMessages;
                2,3:
                begin
                RPLRClear;
                RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
                RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
                RPLRecord.WMDRM_PD:=BackupKey('WDRM');
                writeRpl(PhInfoRecord.IMEIPlain);
                end;
               end;
          end;
   form1.btnFLASH.enabled:=True;
  _msg('Check communication with phone....');
   cs:=s60checkadl;
    case cs of
      $07 :
      begin
      _msg('ADL req restart');
      _msg('Communication verify done... Preparing...');
       TransId:=$5E; MsgBody:=$0A;
       Application.ProcessMessages;
       s60preflashread;

        b:=true;
        //RootHash
        //for i := 0 to $0F do b:=b and (RAPInfo.Root_Key_Hash[i]<>0);
        if BufToHexStr(@RAPInfo.Root_Key_Hash[0],$0F)='00000000000000000000000000000000' then b:=False;
        if Not b then
        begin
          _msg('->  No RootKey Asic! (IMEI DAMAGED?) Unable to continue flashing...');
           enableFLtab;
          SetReady;
          _msg('');
          exit;
        end;
      _msg('Gathering phone info...');
      Application.ProcessMessages;
      //Form1._msg('RAP_BOOT:     '      + BufToHexStr(@RAPInfo.BootID[0],      Length(RAPInfo.BootID)));
      //Form1._msg('RAP_PUBLIC:   '    + BufToHexStr(@RAPInfo.PublicID[0],    Length(RAPInfo.PublicID)));
      //Form1._msg('CMT_ROOTKEY:  '  + BufToHexStr(@RAPInfo.Root_Key_Hash[0], Length(RAPInfo.Root_Key_Hash)));
      //Form1._msg('RAP_PAPUBKEY: '  + BufToHexStr(@RAPInfo.PAPUBKEYSID[0], Length(RAPInfo.PAPUBKEYSID)));
      _msg('Check communication with phone...');
         if s60checkadl<>$07 then begin
         _msg('->  Error while checking phone... Try Flash again...');
         _msg('      Flashing failed...');
         enableFLtab;
         SetReady;
         _msg('');
         exit;
         end;

          batval:=StrToInt(UsbReadBatvalue);
          if batval<3800 then begin
          _msg('Batery valtage : '+inttostr(batval)+' mV');
           case MessageBox(0, 'Batery voltage is low!!! ( less than 3,8V )'+#13+#10+'Do you want continue?', 'Batery voltage check', MB_ICONWARNING or MB_OKCANCEL) of
             idOk: begin
             _msg('-> Batery voltage less, than 3,8V ('+inttostr(batval)+'mV). Continue at user risk');
             end;

             idCancel: begin
                  _msg('-> Batery voltage is low, please, charge');
                  _msg('      Break by user request');
                  _msg('');
                  repairdata;
                  if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
                  Setready;
                  enableFLtab;
                  exit;
                 end ;
            end;
           end;
           Application.ProcessMessages;

         if not chkDOWNGRADE.Checked then
         begin
         Application.ProcessMessages;
         end
         else
         begin
          if not downgradeprep then begin
          _msg('->  Error while prepare for downgrade!');
          _msg('    Break flashing procedure...');
          _msg('    Error while flashing... :(');
          _msg('');
          repairdata;
          if chkDowngrade.checked=true then  chkDowngrade.checked:=False;
          Setready;
          enableFLtab;
          exit;
          end;
         end;
         Application.ProcessMessages;


       Application.ProcessMessages;
       _msg('Reboot....');
       Application.ProcessMessages;

       if not ADLBootInFlash then begin
       _msg('->  Error rebooting phone... Try Flash again...');
       _msg('    Flashing failed...');
       SetReady;
       enableFLtab;
       _msg('');
       exit;
       end;

      if not extractloader(core,2) then
                              begin
                                _msg('->  Boot fail...');
                                _msg('    Flashing failed...');
                                SetReady;
                                _msg('');
                                enableFLtab;
                                exit;
                              end;
      BB5_FlashingXSR15;
      _msg('');
      enableFLtab;
      _msg(setready);
      Application.ProcessMessages;
      DisconnectFill;
      if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
      Exit;
      end;
    else
     begin
     _msg('->  Unknow ADL state['+byte2str(cs)+']... Sorry, continue impossible... :(');
     _msg('    Flashing failed...');
     _msg('');
     enableFLtab;
     SetReady;
     Exit;
     end;
    end;
  end;
 true:
 begin
 form1.btnFLASH.enabled:=True;
 if not extractloader(core,1) then
                              begin
                                _msg('->  Boot fail...');
                                _msg('    Flashing failed...');
                                SetReady;
                                if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
                                _msg('');
                                enableFLtab;
                                exit;
                              end;
 BB5_FlashingXSR15;
 _msg('');
 _msg(setready);
 enableFLtab;
  DisconnectFill;
 if chkDEADMODE.checked=true then  chkDEADMODE.checked:=False;
 Exit;
 end;

 end;
end;


procedure TForm1.OmapBootFlash;
var
  cs:Byte;
  b:boolean;
  i:Integer;
begin

  if (core='') and (chkMCUen.checked=false) and (ppm='') and (chkPPMe.checked=false) then begin
   _msg('');
   _msg('->  Flash Files are not selected');
   _msg('      You can Select:');
   _msg('      MCU+PPM, MCU+PPM+CNT');
   _msg('');
   enableFLtab;
   Exit;
  end;
  Application.ProcessMessages;
        if chkBackup.checked=true then
          begin
               _msg('Backup CRT308 data...');
               _msg(CRT308backup);
               case chksl of
               1:Application.ProcessMessages;
                2,3:
                begin
                RPLRClear;
                RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
                RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
                RPLRecord.WMDRM_PD:=BackupKey('WDRM');
                writeRpl(PhInfoRecord.IMEIPlain);
                end;
               end;
          end;
  _msg('Check communication with phone....');

   cs:=s60checkadl;
   if cs=$00 then begin
   _msg('Try reset phone...');
    if not resetphone then begin
     Application.ProcessMessages;
     Sleep(1500);
     Application.ProcessMessages;
     if not resetphone then _msg('->  Reset failed.... Need flash with SIM Card');
    end;
    Application.ProcessMessages;
    Sleep(1500);
    Application.ProcessMessages;
   end;
  cs:=s60checkadl;

  case cs of
  $02 :
      begin
      _msg('ADL Boot req');
      _msg('Communication verify done... Preparing...');
       TransId:=$5E; MsgBody:=$0A;
       Application.ProcessMessages;
       s60preflashread;

        b:=true;
        //RootHash
       // for i := 0 to $0F do b:=b and (RAPInfo.Root_Key_Hash[i]<>0);
        if BufToHexStr(@RAPInfo.Root_Key_Hash[0],$0F)='00000000000000000000000000000000' then b:=False;
        
        if Not b then
        begin
          _msg('->  No RootKey Asic CMT! (IMEI DAMAGED?) Unable to continue flashing...');
          enableFLtab;
          SetReady;
          _msg('');
          exit;
        end;

         b:=true;
        //RootHash
        for i := 0 to $0F do b:=b and (RAPInfo.APErootkey[i]<>0);

        if Not b then
        begin
          _msg('->  No RootKey Asic APE! Unable to continue flashing...');
          enableFLtab;
          SetReady;
          _msg('');
          exit;
        end;

      _msg('Gathering phone info...');
      Application.ProcessMessages;
      Form1._msg('RAP_BOOT:     '  + BufToHexStr(@RAPInfo.BootID[0],      Length(RAPInfo.BootID)));
      Form1._msg('RAP_PUBLIC:   '  + BufToHexStr(@RAPInfo.PublicID[0],    Length(RAPInfo.PublicID)));
      Form1._msg('CMT_ROOTKEY:  '  + BufToHexStr(@RAPInfo.Root_Key_Hash[0], Length(RAPInfo.Root_Key_Hash)));
      Form1._msg('RAP_PAPUBKEY: '  + BufToHexStr(@RAPInfo.PAPUBKEYSID[0], Length(RAPInfo.PAPUBKEYSID)));
      Form1._msg('APE_ROOTKEY:  '  + BufToHexStr(@RAPInfo.APErootkey[0], Length(RAPInfo.APErootkey)));
      _msg('Check communication with phone...');
         if s60checkadl<>$02 then begin
         _msg('->  Error while checking phone... Try Flash again...');
         _msg('       Flashing failed...');
         SetReady;
         enableFLtab;
         _msg('');
         exit;
         end;
      Application.processMessages;
      starttime;
      Application.ProcessMessages;
           if stop=True then
           begin
           // Stopping operation
               dostop('BOOT');
               Form1.pb1.progress:=0;
               _msg('       Flashing failed...');
               SetReady;
               enableFLtab;
               _msg('');
               exit;
           end;
      case BB5ScanHeader(core) of
      4: begin
          if not OMAP1710boot  then begin
          _msg('->  Error while booting phone... Try Flash again...');
          _msg('       Flashing failed...');
          SetReady;
          enableFLtab;
          _msg('');
          exit;
          end;
          end;
      6: begin
          if not OMAP2420boot  then begin
          _msg('->  Error while booting phone... Try Flash again...');
          _msg('       Flashing failed...');
          SetReady;
          enableFLtab;
          _msg('');
          exit;
          end;
         end;
      8: begin
           case MessageBox(0, 'Warning!!!!'+#13+#10+'PPM Flashing delete ALL User data on phone!!!'+#13+#10+'e.g. PhoneBook, Gallery, MMC Passwords'+#13+#10+'Do You want continue?', 'OMAP 1610 PPM Flash confirm', MB_ICONWARNING or MB_OKCANCEL) of
           idOk: Application.ProcessMessages;
           idCancel: begin
                     _msg('Flashing stopped by user request...');
                     SetReady;
                     enableFLtab;
                     _msg('');
                     exit;

                     end ;
           end;

          if not OMAP1610boot  then begin
          _msg('->  Error while booting phone... Try Flash again...');
          _msg('       Flashing failed...');
          SetReady;
          enableFLtab;
          _msg('');
          exit;
          end;
          end;
      else Exit;
      end;
      Application.ProcessMessages;
      endtimecount;
           if stop=True then
           begin
           // Stopping operation
               dostop('BOOT');
               Form1.pb1.progress:=0;
               _msg('       Flashing failed...');
               SetReady;
               enableFLtab;
               _msg('');
               exit;
           end;
      _msg('TIME : Boot time : '+showtime(tmsres));
      _msg('Reboot....');
      Application.ProcessMessages;
      if not OMAPFlash then begin
      _msg('->  Error while flashing! :(');
      _msg('');
      enableFLtab;
      SetReady;
      Exit;
      end;
      _msg('');
      _msg(setready);
      cltrycn.ShowBalloonHint('BB5 Easy Service Tool Flashing','Flashing done',bitinfo,10);
      _msg('');
      enableFLtab;
      DisconnectFill;
      Application.ProcessMessages;
   end;
   else begin
       _msg('->  Unknow phone ADL req state! ['+byte2str(cs)+']');
       _msg('       Error while flashing! :(');
       _msg('');
       enableFLtab;
       SetReady;
       Exit;
       end;

  end;
end;



{procedure TForm1.Button2Click(Sender: TObject);
var
ms:TMemoryStream;
begin
  SetBuzy;
  ms:=TMemoryStream.Create;
  ms.LoadFromFile('C:\dat.bin');
  FbusSendSynk;
  FbusDelPhoneBookwd2;
  fbuswritefilewd2(ms,'C:\System\DataContacts.cdb');
  ms.Free;
  SetReady;
end;     }


procedure TForm1.Filepresent;
begin
      if (core<>'') or (Form1.chkMCUen.checked=true) then begin
       if not CheckFiles(core) then begin
        core:='';  Form1.chkMCUen.checked:=False; Form1.MCUt.Text:='';
       end;
      end;
      if (ppm<>'') or (Form1.chkPPMe.Checked=True) then  begin
       if not CheckFiles(ppm) then begin
        ppm:='';  Form1.chkPPMe.checked:=False; Form1.PPMt.Text:='';
       end;
      end;
      if (ppm1<>'') or (Form1.chkPPM1e.Checked=True) then begin
       if not CheckFiles(ppm1) then begin
        ppm1:='';  Form1.chkPPM1e.checked:=False;  Form1.PPM1t.Text:='';
       end;
      end;
      if (image<>'') or (Form1.chkCNTe.Checked=True) then  begin
        if not CheckFiles(image) then begin
        image:='';  Form1.chkCNTe.checked:=False;  Form1.CNTt.Text:='';
       end;
      end;
      if (ape<>'') or (Form1.chkAPEe.Checked=True) then begin
        if not CheckFiles(ape) then begin
        ape:='';  Form1.chkAPEe.checked:=False;  Form1.APEt.Text:='';
       end;
      end;
      if (cnt3<>'') or (Form1.chkcnt3.checked=true) then begin
       if not CheckFiles(cnt3) then begin
        cnt3:='';  Form1.chkcnt3.checked:=False; Form1.cnt3t.Text:='';
       end;
      end;
end;
{
procedure TForm1.Button1Click(Sender: TObject);
var
FF,F:TFileStream;
Dir,s:string;
begin
      if SelectDirectory('Select directory for save','',Dir) then begin
       if core <>'' then begin
         s:=Dir+'\'+ExtractFileName(core);
         F:=TFileStream.Create(s,fmCreate);
         FF:=TFileStream.Create(core,fmOpenRead);
         F.CopyFrom(FF,FF.Size);
         F.Free;
         FF.Free;
       _msg('file '+s+' save - Ok');
       end;
       if ppm <>'' then begin
         s:=Dir+'\'+ExtractFileName(ppm);
         F:=TFileStream.Create(s,fmCreate);
         FF:=TFileStream.Create(ppm,fmOpenRead);
         F.CopyFrom(FF,FF.Size);
         F.Free;
         FF.Free;
       _msg('file '+s+' save - Ok');
       end;
       if ppm1 <>'' then begin
         s:=Dir+'\'+ExtractFileName(ppm1);
         F:=TFileStream.Create(s,fmCreate);
         FF:=TFileStream.Create(ppm1,fmOpenRead);
         F.CopyFrom(FF,FF.Size);
         F.Free;
         FF.Free;
       _msg('file '+s+' save - Ok');
       end;
       if image <>'' then begin
         s:=Dir+'\'+ExtractFileName(image);
         F:=TFileStream.Create(s,fmCreate);
         FF:=TFileStream.Create(image,fmOpenRead);
         F.CopyFrom(FF,FF.Size);
         F.Free;
         FF.Free;
       _msg('file '+s+' save - Ok');
       end;
       if ape <>'' then begin
         s:=Dir+'\'+ExtractFileName(ape);
         F:=TFileStream.Create(s,fmCreate);
         FF:=TFileStream.Create(ape,fmOpenRead);
         F.CopyFrom(FF,FF.Size);
         F.Free;
         FF.Free;
       _msg('file '+s+' save - Ok');
       end;
       _msg('Done!');
      end;
end;
}
procedure TForm1.testnrClick(Sender: TObject);
var
s:string;
F:TFileStream;
begin
      s:='C:\Private\100012a5\DBS_100065FF_Contacts.cdb';
      F:=TFileStream.Create('.\a.bin',fmCreate);
      _msg(AperunUni);
//      UsbReadFileS60(F,s);
      S60format('Z');
      F.Free;
end;

procedure TForm1.btnCamConfClick(Sender: TObject);
var
sec:string;
begin
  {$I VM_Start.inc}     
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
  {$I VM_End.inc}

  SetBuzy;
 CheckCamSW;
  SetReady;
end;

procedure TForm1.N0Click(Sender: TObject);
begin
    phsel:=1;
    ChPrdD;
end;

procedure TForm1.N1Click(Sender: TObject);
begin
    phsel:=2;
    ChPrdD;
end;

procedure TForm1.N2Click(Sender: TObject);
begin
    phsel:=3;
    ChPrdD;
end;

procedure TForm1.chClick(Sender: TObject);
begin
 phoenixfolder:=PrdCh(phoenixfolder);
     case phsel of
     1: begin N0.Caption:=phoenixfolder; prd1:=phoenixfolder;end;
     2: begin N1.Caption:=phoenixfolder; prd2:=phoenixfolder;end;
     3: begin N2.Caption:=phoenixfolder; prd3:=phoenixfolder;end;
     end;
end;

procedure TForm1.btnSvUsIniClick(Sender: TObject);
var
userini:TIniFile;
begin
       if PasswordDlg.ShowModal=mrOk then begin
         userini:=TIniFile.Create(StartDir+'userini.ini');
           if PasswordDlg.NameStrIni.Text<>'' then begin
             userini.WriteString(PasswordDlg.NameStrIni.Text,'1',core);
             userini.WriteString(PasswordDlg.NameStrIni.Text,'2',ppm);
             userini.WriteString(PasswordDlg.NameStrIni.Text,'3',ppm1);
             userini.WriteString(PasswordDlg.NameStrIni.Text,'4',image);
             userini.WriteString(PasswordDlg.NameStrIni.Text,'5',ape);
             userini.WriteString(PasswordDlg.NameStrIni.Text,'6',cnt3);
             _msg('User INI update - Ok');
             _msg('');
           end;
          userini.Free;
       end;
end;

procedure TForm1.UserInClick(Sender: TObject);
var
userini:TIniFile;
begin
     if userin.Checked then begin
//        flman.Checked:=false;
        usini.Checked:=false;
         userini:=TIniFile.Create(StartDir+'userini.ini');
         userini.ReadSections(cbbselpc.Items);
         userini.Free;
         if cbbselpc.Items.Count>0 then begin
          cbbSelPC.Enabled:=true;
          cbbSelPC.ItemIndex:=0;
          SelectFiles;
         end;
     end else begin
       MCUt.Text:= '';
       PPMt.Text:= '';
       PPM1t.Text:= '';
       CNTt.Text:= '';
       APEt.Text:= '';
       CNT3t.Text:='';
       chkMCUen.Checked:=false;
       chkPPMe.Checked:=false;
       chkPPM1e.Checked:=false;
       chkCNTe.Checked:=false;
       chkAPEe.Checked:=false;
       chkCNT3.Checked:=false;
       core:='';
       ppm:='';
       ppm1:='';
       image:='';
       ape:='';
       cnt3:='';
       swver:='';
       VplList.Clear;
       cbbSelPC.Clear;
       cbbSelPC.Enabled:=false;
       end;
end;

procedure TForm1.btn1Click(Sender: TObject);
var
  i:integer;
begin
  SetBuzy;
  setready;
  end;

function TForm1.dat2hstr(const s: string; len: dword = 0): string;
var i:   dword;
    buf: string;
begin
   result := '';
   if len = 0 then len := length(s);
   if length(s) = 0 then exit;

   for i := 1 to len do
   begin
     buf := intTohex(ord(s[i]),2);
     case length(buf) of
     0: result := result + '00' + buf;
     1: result := result + '0'  + buf;
     2: result := result + buf;
     end;
  end;
end;

function TForm1.dcp_hash_md5(const data: string): string;
const dcp_md5_size                 = $10;
var  MyMD5: TDCP_md5;
     digest: array[$00..dcp_md5_size-1] of byte;
     i: integer;
begin
  result := StringOfChar(#$FF, dcp_md5_size);
  MyMD5  := TDCP_md5.create(nil);
  MyMD5.init;
  MyMD5.UpdateStr(data);
  MyMD5.Final(digest);
  MyMD5.free;
  for i := 0 to dcp_md5_size-1 do result[i+1] := chr(digest[i]);
end;

function TForm1.support_area_access(const download_area_link: string; const product_key: string; extra_url: string = ''): string;
var cdate, key, buf,user,pass: string;
//http://your-site.com/download?user=demo&pass=demo&key=demo&cdate=demo
begin
  {$I VM_Start.inc}
//  {$I crypt_start.inc}

  result := '';
  user:=GetUser;
  pass:=GetPass;
  cdate := '';
  key   := '';

  buf   := inttostr(YearOf(now()));  if length(buf) < 4 then buf := stringofchar('0', 4-length(buf)) + buf;
  cdate := cdate + buf;
  buf   := inttostr(MonthOf(now())); if length(buf) < 2 then buf := stringofchar('0', 2-length(buf)) + buf;
  cdate := cdate + buf;
  buf   := inttostr(DayOf(now()));   if length(buf) < 2 then buf := stringofchar('0', 2-length(buf)) + buf;
  cdate := cdate + buf;
  //YYYYmmdd
  key   := dat2hstr(dcp_hash_md5(user + cdate + product_key + pass + cdate));

  if length(key) > 0 then
  result := download_area_link + '/index-3.php'+
                                 '?user='+user+
                                 '&pass='+pass+
                                 '&cdate='+cdate+
                                 '&key='+key+
                                 extra_url;
  {$I VM_End.inc}
//  {$I crypt_end.inc}
end;

procedure TForm1.BitBtn1Click(Sender: TObject);
var
di:TIniFile;
s:string;
begin
   di:=TIniFile.Create(StartDir+'settings.ini');
   s:=di.ReadString('Download',suppar.Items.Strings[suppar.ItemIndex],'http://server1.infinity-best.com/download');
   di.Free;
   s:=support_area_access(PChar(s),'pemrufbsloenehdn');
//   _msg(s);
   ShellExecute(Handle, nil,PChar(s), nil, nil, SW_SHOW);
end;

procedure TForm1.cltrycnClick(Sender: TObject);
begin
Application.ProcessMessages;
cltrycn.ShowMainForm;
Application.ProcessMessages;
cltrycn.IconVisible:=False;
Application.ProcessMessages;
end;


procedure TForm1.btnReadRPLClick(Sender: TObject);
var
  i,i2      : Integer;
  cs        : Byte;
  crs       : string;
begin
      {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    crs:=CardPass(crpass);
    if crs <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  imei_global:='';
  RPLRClear;
  if ConMode=1 then DisUfsButton;
 _msg('Backup Certificates now...');
 if (ConMode=1) and (fbdev=1) then
 begin
   case PhonePresentmode of
   $00:
    begin
    BUsCheck;
     if boot_done=true then
     begin
     grabrpl(1);
     UFSfinishsession;
     if apeexist then UFSEBLockAPE;
     UFSfinishsession;
     UFSEBLock;
     end;
     if InitServiceMode then
     begin
      if not ReadPhoneInfoall then _msg('Error on initial info reading :(');
      StatusBar.Panels.Items[0].Text :=PhInfoRecord.PhType+' '+PhInfoRecord.Name;
      StatusBar.Panels.Items[1].Text :='MCU '+Copy(PhInfoRecord.MCUSW,1,7)+'; APE  '+PhInfoRecord.APECoreSW;
      StatusBar.Panels.Items[1].Text :=PhInfoRecord.IMEIPlain;
      if (PhInfoRecord.IMEIPlain<>'') and (PhInfoRecord.IMEIPlain<>'Error') then imei_global:=PhInfoRecord.IMEIPlain;
      Application.ProcessMessages;
      RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
      RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
      RPLRecord.WMDRM_PD:=BackupKey('WDRM');
      form1._msg(CRT308backup);
     end
     else Form1._msg('Init service mode fail! Can'+#39+'t read flex keys');
    end;
   $01:
    begin
     imei_global:=statusbar.Panels.Items[2].Text;
     RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
     RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
     RPLRecord.WMDRM_PD:=BackupKey('WDRM');
     form1._msg(CRT308backup);
     BUsCheck;
     if boot_done=true then
     begin
     grabrpl(1);
     UFSfinishsession;
     UFSfinishsession;
     UFSEBLock;
     end;
    end;
   end;
  writeRpl(imei_global);
  statusbar.Panels.Items[1].text:='';
  DisconnectFill;
  EnUfsbutton;
  SetReady;
  Exit;
  end;
 case PhonePresentmode of
 $00: // DEAD mode
  begin
   if not ExtractloaderXSRRap3Gv4(1) then
   begin
   _msg('Looks like ASIC not supported, or HW failure');
   _msg('Supported : RapuYama, RAP3Gv4, BroadComm');
   _msg('Try Flash latest SW and repeat, if phone in supported list');
   _msg('');
   setready;
   Exit;
   end;

     fltime:=0;
     Form1._msg('Reopening the connection...');
     Application.ProcessMessages;
     Sleep(500);
     Application.ProcessMessages;

     i:=30;
     while i>0 do
     begin
          Form1._msg('Waiting for response: '+inttostr(i));
          Application.ProcessMessages;
          if catchdevice<>$02 then
          begin
          Application.ProcessMessages;
          sleep (1000);
          Application.ProcessMessages;
          end
          else i:=0;
          dec(i);
     end;

     if not DevPresent then
     begin
          Form1._msg('Phone not found... :(');
          Form1._msg('');
          Form1.StatusBar.Panels[4].Text:='';
          //writeRpl(imei_global);
          SetReady;
          USBClosePort;
          exit;
     end;

    RAPnewChkADL;

    Form1._msg('ADL: Reading certificates...');
    Form1._msg('');
     grabrpl(0);
    { bufferrd:=TMemoryStream.Create;
     bufferrd.LoadFromFile('C:\FF.bin');
     buildxsr16cert(bufferrd,'NPC'); }
    Form1._msg('ADL: Reading certificates done! :)');
    RapNewFinishLocal;
    Form1._msg('');
    Form1._msg('Wait, reconneting...');
    Form1._msg('');
    Application.ProcessMessages;
            //Sleep(1000);
            //Application.ProcessMessages;
            i:=1200;
            while i>0 do
            begin
            //Form1._msg('Waiting for response: '+inttostr(i));
            Application.ProcessMessages;
             if catchdevice<>$01 then
             begin
             Application.ProcessMessages;
             sleep (100);
             Application.ProcessMessages;
             Form1.StatusBar.Panels[1].Text:=IntToStr(i);
             end
             else i:=0;
             dec(i);
            end;
            if not DevPresent then
            begin
            Form1._msg('Phone not found... :(');
            Form1._msg('CertRead failed : phone was not bootup');
            Form1._msg('Connection/SW/HW problem, try bootup manually');
            Form1._msg('');
            Form1.StatusBar.Panels[4].Text:='';
            SetReady;
            if chkDEADMODE.checked=true then chkDEADMODE.checked:=false;
            writeRpl(imei_global);
            USBClosePort;
            exit;
            end;
   case chksl of
    1:
    begin
     Application.ProcessMessages;
    end;
    2,3:
    begin
    RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
    RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
    RPLRecord.WMDRM_PD:=BackupKey('WDRM');
    form1._msg(CRT308backup);
    end;
   end;
    writeRpl(imei_global);
    Form1._msg('All done, Disconnecting');
    Application.ProcessMessages;
    Sleep(1000);
    Application.ProcessMessages;
  end;
 $01: // Normal mode
  begin
   _msg('Backup CRT308 data...');
   _msg(CRT308backup);
   imei_global:=PhInfoRecord.IMEIPlain;
   case chksl of
    1:
    begin
     Application.ProcessMessages;
    end;
    2,3:
    begin
    RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
    RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
    RPLRecord.WMDRM_PD:=BackupKey('WDRM');
    end;
   end;
   Application.ProcessMessages;
   _msg('Check communication with phone....');
   cs:=s60checkadl;
   if cs=$07 then begin
      Application.ProcessMessages;
      _msg('Reboot....');
      Application.ProcessMessages;

       if not ADLBootInFlash then begin
       _msg('->  Error rebooting phone... Try Flash again...');
       _msg('    Flashing failed...');
       SetReady;
       enableFLtab;
       writeRpl(imei_global);
       _msg('');
       exit;
       end;

       if not ExtractloaderXSRRap3Gv4(0) then
       begin
        _msg('Looks like ASIC not supported, or HW failure');
        _msg('Supported : RapuYama, RAP3Gv4, BroadComm');
        _msg('Try Flash latest SW and repeat, if phone in supported list');
        _msg('');
        writeRpl(imei_global);
        setready;
        Exit;
        end;

     fltime:=0;
     Form1._msg('Reopening the connection...');
     Application.ProcessMessages;
     Sleep(500);
     Application.ProcessMessages;

     i:=30;
     while i>0 do
     begin
          Form1._msg('Waiting for response: '+inttostr(i));
          Application.ProcessMessages;
          if catchdevice<>$02 then
          begin
          Application.ProcessMessages;
          sleep (1000);
          Application.ProcessMessages;
          end
          else i:=0;
          dec(i);
     end;

     if not DevPresent then
     begin
          Form1._msg('Phone not found... :(');
          Form1._msg('');
          Form1.StatusBar.Panels[4].Text:='';
          writeRpl(imei_global);
          SetReady;
          USBClosePort;
          exit;
     end;

    RAPnewChkADL;

    Form1._msg('ADL: Reading certificates...');
    Form1._msg('');
     grabrpl(0);
    Form1._msg('ADL: Reading certificates done! :)');
    RapNewFinish;

    _msg('');

    writeRpl(imei_global);

    Form1._msg('All done, Disconnecting');
    Application.ProcessMessages;
    Sleep(1000);
    Application.ProcessMessages;
   end
   else
   begin
   Form1._msg('ADL not support backup mode, rpl reading impossible');
   writeRpl(imei_global);
   end;
  end;
 end;
_msg('');
_msg(setready);
 DisconnectFill;
_msg('');
end;

procedure Tform1.BUsCheck();
var
  bflag   : boolean;
  tryinit : integer;
  len     : word;
begin
    boot_done:=false;
  //_msg('Checking BUS...');
  _msg('Setting FlashMode');
 //SetBuzy;
 tryinit:=0;
 bflag:=false;
 repeat
  bflag:=ufx_sw_fbus(fbnum,'FlashBus');
  Application.ProcessMessages;
  Inc(tryinit);
  if tryinit=2
  then
  begin
    if (ufx_boot(fbnum)) then
    begin
    ufx_sw_fbus(fbnum,'FlashBus');
    Application.ProcessMessages;
    end
    else
    tryinit:=5;
  end;
  if bflag=true then break;
 until tryinit=5;

 if not bflag then
 begin
 _msg('UFSx : FlashMode init fail! Reconnect box');
 _msg('');
 boot_done:=false;
 SetReady;
 exit;
 end;
 Form1.statusbar.Panels[0].Text:='UFS : Booting phone...';
 ufs_cmd(3500,@CMTread[0],2,@cmd_buf,200);
 //Form1._msg('BootData : '+BufToHexStr(@cmd_buf[0], $FF));
 Application.ProcessMessages;
 if (cmd_buf[1]>20) and (cmd_buf[2]=$C0) then FetchBootData
 else
 begin
 _msg('No answer from phone... :(');
 _msg('1. Check cable/connection, try again');
 _msg('2. Maybe HW fault or bad cable');
 _msg('');
 SetReady;
 Exit;
 end;

 if ROOTcheck<>True then
 begin
 Form1._msg('UFSx doesn'+#39+'t support New Protocol :(');
 _msg('');
 SetReady;
 Exit;
 end;

 if not FbusSelLoader2nd(Fasiccmt) then
 begin
 Form1._msg('Error finding required loader... :(');
 _msg('');
 SetReady;
 Exit;
 end;

 case SendRaw(0,FbusFloader) of
 0: Application.ProcessMessages;
 9: begin
    Form1._msg('Error on prepare stage - connection fail or HW error');
    Form1._msg('');
    Exit;
    end;
 8: begin
    Form1._msg('Error on prepare 2nd boot');
    form1._msg('');
    Exit;
    end;
 7: begin
    Form1._msg('Error on initial 2nd boot');
    form1._msg('');
    Exit;
    end;
 6: begin
    Form1._msg('Error : 2nd boot not accepted');
    form1._msg('RX : '+buftohexstr(@Ft_in_buffer[0],10));
    form1._msg('');
    Exit;
    end;
 5: begin
    Form1._msg('Error : info stage failed - check connection , HW');
    form1._msg('');
    Exit;
    end;
 4: begin
    Form1._msg('Error on prepare target for algo');
    form1._msg('');
    Exit;
    end;
 end;
 FbusSelLoader2nd(Fasiccmt);
 case SendAlgorihtm(0,FbusSloader) of
 0: Application.ProcessMessages;
 9: begin
    Form1._msg('Error on prepare stage - connection fail or HW error');
    Form1._msg('');
    Exit;
    end;
 8: begin
    Form1._msg('Error on prepare for algo');
    form1._msg('');
    Exit;
    end;
 7: begin
    Form1._msg('Error : algorithm not accepted');
    form1._msg('');
    Exit;
    end;
 6: begin
    Form1._msg('Error : info stage failed - check connection , HW');
    form1._msg('');
    Exit;
    end;
 end;
 PreCertreq;
 if apeexist then
 begin
  if not FbusSelLoader2nd(Fasicape) then begin
  Form1._msg('Error finding required loader... :(');
  _msg('');
  SetReady;
  Exit;
  end;
  case SendRaw(1,FbusFloader) of
    0: Application.ProcessMessages;
    9: begin
    Form1._msg('Error on prepare stage - connection fail or HW error');
    Form1._msg('');
    Exit;
    end;
    8: begin
    Form1._msg('Error on prepare 2nd boot');
    form1._msg('');
    Exit;
    end;
    7: begin
    Form1._msg('Error on initial 2nd boot');
    form1._msg('');
    Exit;
    end;
    5: begin
    Form1._msg('Error : 2nd boot not accepted');
    form1._msg('');
    Exit;
    end;
    6: begin
    Form1._msg('Error : info stage failed - check connection , HW');
    form1._msg('');
    Exit;
    end;
    4: begin
    Form1._msg('Error on prepare target for algo');
    form1._msg('');
    Exit;
    end;
  end;
  FbusSelLoader2nd(Fasicape);
  if not FbusSelLoader2nd(Fasicape) then begin
  Form1._msg('Error finding required loader... :(');
  _msg('');
  SetReady;
  Exit;
  end;
  case  SendAlgorihtm(1,FbusSloader) of
  0: Application.ProcessMessages;
  9: begin
    Form1._msg('Error on prepare stage - connection fail or HW error');
    Form1._msg('');
    Exit;
    end;
  8: begin
    Form1._msg('Error on prepare for algo');
    form1._msg('');
    Exit;
    end;
  7: begin
    Form1._msg('Error : algorithm not accepted');
    form1._msg('');
    Exit;
    end;
  6: begin
    Form1._msg('Error : info stage failed - check connection , HW');
    form1._msg('');
    Exit;
    end;
  end;
 end;
 //PreCertreq;
 _msg('');
 _msg('Boot Done!');
   boot_done:=true;
 _msg('');
end;

procedure Tform1.BUsCheckCMTonly();
var
  bflag   : boolean;
  tryinit : integer;
  len     : word;
begin
    boot_done:=false;
  //_msg('Checking BUS...');
  _msg('Setting FlashMode');
 SetBuzy;
 tryinit:=0;
 bflag:=false;
 repeat
  bflag:=ufx_sw_fbus(fbnum,'FlashBus');
  Application.ProcessMessages;
  Inc(tryinit);
  if tryinit=2
  then
  begin
    if (ufx_boot(fbnum)) then
    begin
    ufx_sw_fbus(fbnum,'FlashBus');
    Application.ProcessMessages;
    end
    else
    tryinit:=5;
  end;
  if bflag=true then break;
 until tryinit=5;
 if not bflag then
 begin
 _msg('UFSx : FlashMode init fail! Reconnect box');
 _msg('');
 boot_done:=false;
 SetReady;
 exit;
 end;
 Form1.statusbar.Panels[0].Text:='UFS : Booting phone...';
 ufs_cmd(3500,@CMTread[0],2,@cmd_buf,200);
 //Form1._msg('BootData : '+BufToHexStr(@cmd_buf[0], $FF));
 Application.ProcessMessages;
 if (cmd_buf[1]>20) and (cmd_buf[2]=$C0) then FetchBootData
 else
 begin
 _msg('No answer from phone... :(');
 _msg('1. Check cable/connection, try again');
 _msg('2. Maybe HW fault or bad cable');
 _msg('');
 SetReady;
 Exit;
 end;

 if ROOTcheck<>True then
 begin
 Form1._msg('UFSx doesn'+#39+'t support New Protocol :(');
 _msg('');
 SetReady;
 Exit;
 end;

 if not FbusSelLoader2nd(Fasiccmt) then
 begin
 Form1._msg('Error finding required loader... :(');
 _msg('');
 SetReady;
 Exit;
 end;

 case SendRaw(0,FbusFloader) of
 0: Application.ProcessMessages;
 9: begin
    Form1._msg('Error on prepare stage - connection fail or HW error');
    Form1._msg('');
    Exit;
    end;
 8: begin
    Form1._msg('Error on prepare 2nd boot');
    form1._msg('');
    Exit;
    end;
 7: begin
    Form1._msg('Error on initial 2nd boot');
    form1._msg('');
    Exit;
    end;
 6: begin
    Form1._msg('Error : 2nd boot not accepted');
    form1._msg('RX : '+buftohexstr(@Ft_in_buffer[0],10));
    form1._msg('');
    Exit;
    end;
 5: begin
    Form1._msg('Error : info stage failed - check connection , HW');
    form1._msg('');
    Exit;
    end;
 4: begin
    Form1._msg('Error on prepare target for algo');
    form1._msg('');
    Exit;
    end;
 end;
 case SendAlgorihtm(0,FbusSloader) of
 0: Application.ProcessMessages;
 9: begin
    Form1._msg('Error on prepare stage - connection fail or HW error');
    Form1._msg('');
    Exit;
    end;
 8: begin
    Form1._msg('Error on prepare for algo');
    form1._msg('');
    Exit;
    end;
 7: begin
    Form1._msg('Error : algorithm not accepted');
    form1._msg('');
    Exit;
    end;
 6: begin
    Form1._msg('Error : info stage failed - check connection , HW');
    form1._msg('');
    Exit;
    end;
 end;
 PreCertreq;
 _msg('');
 _msg('Boot Done!');
   boot_done:=true;
 _msg('');
end;

procedure TForm1.btnUFSconnectClick(Sender: TObject);
begin
  SetBuzy;
  try
  Close_USB_Device;
  except
  Application.ProcessMessages;
  end;
  BArmInterface;
  fbdev:=1;
  ConMode:=1;
  checkbtn.enabled:=true;
  btnWriteRPL.Enabled:=True;
end;

procedure TForm1.btnPartitionClick(Sender: TObject);
var
s:string;
begin
   {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

  SetBuzy;
  BUsCheck;
  if boot_done then
   begin
   grabrpl(1);
   //if not readUIDstep1 then form1._msg('Error fetching data... :(') else form1._msg('ID read done ;)');
   _msg('');
   end
  else begin
  _msg('Initial boot fail, fetching impossible. Check connection');
  end;
  SetReady;
end;

procedure TForm1.btnSmlkClick(Sender: TObject);
begin
setbuzy;

end;

procedure TForm1.btnGrabFSClick(Sender: TObject);
label retry;
var
i,Len,flen       :integer;
path,fpath,tpath :String;
FL               :TStrings;
i2,ercnt         :integer;
F                :TFileStream;
s                :string;
ret              :integer;
image            :TMemoryStream;
SucFCount        :word;
ImFlen           :dword;
strlen,Dbyte     :Byte;
dbuf             :array of Byte;
begin
  {$I VM_Start.inc}
//   {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

 SetBuzy;
   flen:=0;
   FL:=TStringList.Create;
    _msg('Getting All FS data : [Image]');
    _msg('Generation mode : [S40]');
      if not s40drvscan then path:=Utf8Encode('c:\') else path:=Utf8Encode('s:\');
   //_msg('List of '+path+' directory');
   _msg('Scanning FileSystem..');
   //_msg(GetUsbDir(path));
   if ScanProcess then begin Application.Terminate; exit; end;
   GetS40FileList(FL,path);
   _msg('Scan done, processing data...');
   _msg('Total - '+IntToStr(FL.Count)+' files');
       pb1.maxvalue:=FL.Count;
       Application.ProcessMessages;
    FL.SaveToFile('.\'+StatusBar.Panels.Items[2].Text+'\'+'dirtree.txt');
    Form1._msg('DirTree saved');
    Image:=TMemoryStream.create;
    image.WriteBuffer(DataHeader,length(DataHeader));
    SucFcount:=0;
    Dbyte:=$DF;
     for i:=0 to FL.Count-1 do begin
      len:=0;
       // Len:=StrToInt(Copy(FL.Strings[i],1,(Pos(':',FL.Strings[i])-1)));
      fpath:=FL.Strings[i];
           //_msg('Reading');
           //_msg(IntToStr(Len));
           //_msg(Utf8Decode(fpath));
           //_msg('');
      tpath:=fpath;
      Delete(fpath,1,3);
      path:='.\'+StatusBar.Panels.Items[2].Text+'\'+Utf8ToAnsi(fpath);
          //_msg(tpath);
          //if not DirectoryExists(ExtractFilePath(path)) then CreateDir(ExtractFilePath(path));
     // try
       Len:=s40getsizeuni(tpath);
       if ConMode=1 then FbusSendSynk;
       //_msg(IntToStr(Len));
        if Len>0 then
        begin
        flen:=flen+len;
        M:=TmemoryStream.Create;
        if not s40extractuni(M,tpath,Len,2) then
         begin
         goto retry;
         retry :
         case MessageBox(0, 'Read error detected!'+#13+#10+''+#13+#10+'Looks like connection lost.'+#13+#10+'Please - Repower/Reconnect phone and press Retry.'+#13+#10+''+#13+#10+'Also You can Ignore that error or cancel reading.', 'Read Error', MB_ICONWARNING or MB_ABORTRETRYIGNORE) of
         idAbort: begin
                  FL.free;
                  _msg('Aborted by User...');
                  _msg('');
                  form1.pb1.progress:=0;
                  form1.pbsm1.progress:=0;
                  setready;
                  exit;
                  end;
         idRetry: begin
                   case ConMode of
                   0:
                    begin
                     _msg('Try again.... (wait 10 sec)');
                      ret:=0;
                      repeat
                      Application.ProcessMessages;
                      sleep(20);
                      inc(ret);
                      until (ret=500) or (catchdevice=$01);
                      if ret<>500 then begin
                     if not s40extractuni(M,tpath,Len,2)
                     then goto retry;
                     end
                     else
                     begin
                       FL.free;
                       _msg('Connection with phone lost... Abort procedure... :(');
                       _msg('');
                       form1.pb1.progress:=0;
                       form1.pbsm1.progress:=0;
                       setready;
                       exit;
                       end;
                    end;
                    1:
                    begin
                      _msg('Try again.... (wait 5 sec)');
                      ret:=0;
                      repeat
                      Application.ProcessMessages;
                      sleep(10);
                      inc(ret);
                      until ret=500;
                     FbusSendSynk;
                     if not s40extractuni(M,tpath,Len,2)
                     then  goto retry;
                    end;
                   end;
                  end;
         idIgnore: begin
                    case ConMode of
                    0:
                    begin
                      _msg('Ignore Read Error... (wait 10 sec)');
                     ret:=0;
                     repeat
                     Application.ProcessMessages;
                     sleep(20);
                     inc(ret);
                     until (ret=500) or (catchdevice=$01);
                     if ret<>500 then Application.ProcessMessages
                     else
                     begin
                     FL.free;
                       _msg('Connection with phone lost... Abort procedure... :(');
                       _msg('');
                       form1.pb1.progress:=0;
                       form1.pbsm1.progress:=0;
                       setready;
                       exit;
                     end;
                    end;
                    1:
                    begin
                     _msg('Ignore Read Error... (wait 5 sec)');
                     ret:=0;
                     FbusSendSynk;
                     repeat
                     Application.ProcessMessages;
                     sleep(10);
                     inc(ret);
                     until (ret=500);
                     Fbussendsynk;
                    end;
                   end;
                  end;
         end;
         end;

        end;
        M.Seek(0,soFromBeginning);
        if M.Size>0 then
        begin
        try
        image.Writebuffer(Dbyte,1);
        strlen:=Length(tpath);
        image.Writebuffer(strlen,1);
        ImFlen:=M.Size;
        DWordSwap(@imFlen);
        image.Writebuffer(imFlen,4);
        image.Writebuffer(tpath[1],strlen);
        image.CopyFrom(M,M.size);
        SucFcount:=SucFcount+1;
        except
        form1._msg('Data convert Error!');
        end;
        end;
        M.Free;

       if ConMode=1 then FbusSendSynk;
       pb1.progress:=pb1.progress+1;
       //sleep(200);
    end;
   //form1._msg(inttostr(SucFcount));
   Wordswap(@SucFcount);
   image.Seek(52,soFromBeginning);
   image.Writebuffer(SucFcount,2);
   image.savetofile('.\'+rightfilename(StatusBar.Panels.Items[2].Text)+'.image_fs');
    _msg ('Image saved as : '+StatusBar.Panels.Items[2].Text+'.image_fs');
   image.free;
   calcsize(flen);
  _msg ('Read Done !');
  _msg ('');
   pb1.MaxValue:=100;
   pb1.Progress:=0;
   FL.Free;
   _msg(SetReady);
  _msg ('');
end;


procedure Tform1.ReadDataType(datatype:string ; Dtapath:string; imagenameL:string);
label retry;
var
i,Len,flen       :integer;
path,fpath,tpath :String;
FL               :TStrings;
i2,ercnt         :integer;
F                :TFileStream;
s                :string;
ret              :integer;
image            :TMemoryStream;
SucFCount        :word;
ImFlen           :dword;
strlen,Dbyte     :Byte;
dbuf             :array of Byte;
begin
   flen:=0;
   FL:=TStringList.Create;
    _msg('Read Package : ['+Datatype+']');
    _msg('Generation mode : [S40]');
    path:=dtapath;
   //_msg('List of '+path+' directory');
   //_msg('Scanning FileSystem..');
   //_msg(GetUsbDir(path));
   if ScanProcess then begin Application.Terminate; exit; end;
   SilentGetS40FileList(FL,path);
   //_msg('Scan done, processing data...');
   //_msg('Total - '+IntToStr(FL.Count)+' files');
       pb1.maxvalue:=FL.Count;
       Application.ProcessMessages;
    // FL.SaveToFile('.\'+StatusBar.Panels.Items[2].Text+'\'+'dirtree.txt');
   // Form1._msg('DirTree saved');
    Image:=TMemoryStream.create;
    image.WriteBuffer(dataheader2,length(dataheader2));
    SucFcount:=0;
    Dbyte:=$DF;
     for i:=0 to FL.Count-1 do
    begin
      len:=0;
       // Len:=StrToInt(Copy(FL.Strings[i],1,(Pos(':',FL.Strings[i])-1)));
      fpath:=FL.Strings[i];
           //_msg('Reading');
           //_msg(IntToStr(Len));
           //_msg(Utf8Decode(fpath));
           //_msg('');
      tpath:=fpath;
      Delete(fpath,1,3);
      //path:='.\'+StatusBar.Panels.Items[2].Text+'\';
          //_msg(tpath);
          //if not DirectoryExists(ExtractFilePath(path)) then CreateDir(ExtractFilePath(path));
     // try
       Len:=s40getsizeuni(tpath);
       if ConMode=1 then FbusSendSynk;
       //_msg(IntToStr(Len));
        if Len>0 then
        begin
        flen:=flen+len;
        M:=TmemoryStream.Create;
        if not s40extractuni(M,tpath,Len,2) then
         begin
         goto retry;
         retry :
         case MessageBox(0, 'Read error detected!'+#13+#10+''+#13+#10+'Looks like connection lost.'+#13+#10+'Please - Repower/Reconnect phone and press Retry.'+#13+#10+''+#13+#10+'Also You can Ignore that error or cancel reading.', 'Read Error', MB_ICONWARNING or MB_ABORTRETRYIGNORE) of
         idAbort: begin
                  FL.free;
                  _msg('Aborted by User...');
                  _msg('');
                  form1.pb1.progress:=0;
                  form1.pbsm1.progress:=0;
                  setready;
                  exit;
                  end;
         idRetry: begin
                   case ConMode of
                   0:
                    begin
                     _msg('Try again.... (wait 10 sec)');
                      ret:=0;
                      repeat
                      Application.ProcessMessages;
                      sleep(20);
                      inc(ret);
                      until (ret=500) or (catchdevice=$01);
                      if ret<>500 then begin
                     if not s40extractuni(M,tpath,Len,2)
                     then goto retry;
                     end
                     else
                     begin
                       FL.free;
                       _msg('Connection with phone lost... Abort procedure... :(');
                       _msg('');
                       form1.pb1.progress:=0;
                       form1.pbsm1.progress:=0;
                       setready;
                       exit;
                       end;
                    end;
                    1:
                    begin
                      _msg('Try again.... (wait 5 sec)');
                      ret:=0;
                      repeat
                      Application.ProcessMessages;
                      sleep(10);
                      inc(ret);
                      until ret=500;
                     FbusSendSynk;
                     if not s40extractuni(M,tpath,Len,2)
                     then  goto retry;
                    end;
                   end;
                  end;
         idIgnore: begin
                    case ConMode of
                    0:
                    begin
                      _msg('Ignore Read Error... (wait 10 sec)');
                     ret:=0;
                     repeat
                     Application.ProcessMessages;
                     sleep(20);
                     inc(ret);
                     until (ret=500) or (catchdevice=$01);
                     if ret<>500 then Application.ProcessMessages
                     else
                     begin
                     FL.free;
                       _msg('Connection with phone lost... Abort procedure... :(');
                       _msg('');
                       form1.pb1.progress:=0;
                       form1.pbsm1.progress:=0;
                       setready;
                       exit;
                     end;
                    end;
                    1:
                    begin
                     _msg('Ignore Read Error... (wait 5 sec)');
                     ret:=0;
                     FbusSendSynk;
                     repeat
                     Application.ProcessMessages;
                     sleep(10);
                     inc(ret);
                     until (ret=500);
                     Fbussendsynk;
                    end;
                   end;
                  end;
         end;
         end;

        end;
        M.Seek(0,soFromBeginning);
        if M.Size>0 then
        begin
        try
        image.Writebuffer(Dbyte,1);
        strlen:=Length(tpath);
        image.Writebuffer(strlen,1);
        ImFlen:=M.Size;
        DWordSwap(@imFlen);
        image.Writebuffer(imFlen,4);
        image.Writebuffer(tpath[1],strlen);
        image.CopyFrom(M,M.size);
        SucFcount:=SucFcount+1;
        except
        form1._msg('Data convert Error!');
        end;
        end;
        M.Free;

       if ConMode=1 then FbusSendSynk;
       pb1.progress:=pb1.progress+1;
       //sleep(200);
    end;
   //form1._msg(inttostr(SucFcount));
   Wordswap(@SucFcount);
   image.Seek(52,soFromBeginning);
   image.Writebuffer(SucFcount,2);
   image.Seek(0,soFromBeginning);
   if image.Size>0 then
   begin
   F:=TFileStream.Create(imagenameL,fmCreate);
   //savecalasText(M,copy(SaveDialog.FileName,0,Length(SaveDialog.FileName)-6)+'_calendar.txt');
   EncryptF(image,F,fullid);
   F.Free;
   _msg ('Saved to : '+imagenamel);
   end;
   //image.savetofile(imagenameL);
   image.free;
   //calcsize(flen);
  _msg ('Read Done !');
  _msg ('');
   pb1.MaxValue:=100;
   pb1.Progress:=0;
   FL.Free;
   _msg(SetReady);
  _msg ('');
end;

procedure TForm1.btnClearFSClick(Sender: TObject);
var
i,Len,flen       :integer;
path,fpath,tpath :String;
FL               :TStrings;
s                :string;
begin
  {$I VM_Start.inc}
//   {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

 SetBuzy;
   flen:=0;
   FL:=TStringList.Create;
    _msg('Clear FS now...');
    _msg('Generation mode : Vertu [S40]');
      if not s40drvscan then path:=Utf8Encode('c:\') else path:=Utf8Encode('s:\');
   //_msg('List of '+path+' directory');
   _msg('Scanning FileSystem..');
   //_msg(GetUsbDir(path));
   if ScanProcess then begin Application.Terminate; exit; end;
   GetS40FileList(FL,path);
   _msg('Scan done, processing data...');
   _msg('Total - '+IntToStr(FL.Count)+' files');
       pb1.maxvalue:=FL.Count;
       Application.ProcessMessages;
     for i:=0 to FL.Count-1 do begin
      Application.ProcessMessages;
      fpath:=FL.Strings[i];
      tpath:=fpath;
      Delete(fpath,1,3);
      if ConMode=1 then FbusSendSynk;
      changerigts($0020,tpath);
      Application.ProcessMessages;
      if not s40delfileuni(tpath) then
      begin
      if ConMode=1 then FbusSendSynk;
      changerigts($0020,tpath);
      Application.ProcessMessages;
      if not s40delfileuni(tpath) then
      Form1._msg('DeleteFile error, skip');
      Application.ProcessMessages;
      end;
       pb1.progress:=pb1.progress+1;
       Application.ProcessMessages;
    end;
  _msg ('Clear Done !');
  _msg ('');
   pb1.MaxValue:=100;
   pb1.Progress:=0;
   FL.Free;
   _msg(SetReady);
  _msg ('');
end;

procedure TForm1.btnReadUniqDataClick(Sender: TObject);
var
s:string;
begin
   {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

  SetBuzy;
  {BUsCheck;
  if boot_done then
   begin
   //grabrpl(1);
   if not readUIDstep1 then form1._msg('Error fetching data... :(') else form1._msg('ID read done ;)');
   _msg('');
   end
  else begin
  _msg('Initial boot fail, fetching impossible. Check connection');
  end;     }
  UkeyClear;
  if not readUIDstep1 then form1._msg('Error fetching data... :(') else form1._msg('ID read done ;)');
   _msg('');
end;

procedure TForm1.UFSFlashing;
var
  x,bp,fp,b : Boolean;
begin
  x:=false;
  bp:=false;
  fp:=false;
  b:=False;
  btnFLASH.enabled:=True;
 if stop=True then
 begin
 dostop('PREPARE/BOOT');
 Application.ProcessMessages;
 Form1._msg('');
 DisconnectFill;
 SetReady;
 Exit;
 end;

 if chkBackup.Checked=True then
 begin
   Form1._msg('Backup enabled, Will read Certificates now...');
   case PhonePresentmode of
   $00:
    begin
    BUsCheck;
     if boot_done=true then
     begin
     grabrpl(1);
     UFSfinishsession;
     if apeexist then UFSEBLockAPE;
     UFSfinishsession;
     UFSEBLock;
     bp:=true;
     end;
     if InitServiceMode then
     begin
      if not ReadPhoneInfoall then _msg('Error on initial info reading :(');
      StatusBar.Panels.Items[0].Text :=PhInfoRecord.PhType+' '+PhInfoRecord.Name;
      StatusBar.Panels.Items[1].Text :='MCU '+Copy(PhInfoRecord.MCUSW,1,7)+'; APE  '+PhInfoRecord.APECoreSW;
      StatusBar.Panels.Items[1].Text :=PhInfoRecord.IMEIPlain;
      if (PhInfoRecord.IMEIPlain<>'') and (PhInfoRecord.IMEIPlain<>'Error') then imei_global:=PhInfoRecord.IMEIPlain;
      Application.ProcessMessages;
      form1._msg(CRT308backup);
      RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
      RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
      RPLRecord.WMDRM_PD:=BackupKey('WDRM');
      fp:=true;
     end
     else
     begin
     form1._msg('Init Service Mode Failed!');
     Application.ProcessMessages;
     end;
    end;
   $01:
    begin
     RPLRecord.SIMLOCK:=BackupKey('SIMLOCK');
     RPLRecord.SIMLOCK_KEY:=BackupKey('SLDdata');
     RPLRecord.WMDRM_PD:=BackupKey('WDRM');
     form1._msg(CRT308backup);
     fp:=true;
     BUsCheck;
     if boot_done=true then
     begin
     grabrpl(1);
     UFSfinishsession;
     UFSfinishsession;
     UFSEBLock;
     bp:=true;
     end;
    end;
   end;
   if (bp=false) and (fp=false) then
   begin
    case MessageBox(0, 'Error while backup CRT Data!!!'+#13+#10+'If SW in phone corrupted - need reflash phone.'+#13+#10+'Continue?', 'Cert Backup Error!', MB_ICONWARNING or MB_YESNO) of
    idYes: Application.ProcessMessages ;
    idNo:
     begin
      form1._msg('Error backup Certificates... :(');
      Form1._msg('');
      DisconnectFill;
      SetReady;
      Exit;
     end;
    end;
    form1._msg('Certificate read error, try continue flashing...');
   end
   else writeRpl(imei_global);
   statusbar.Panels.Items[1].text:='';
 end;

 if stop=True then
 begin
 dostop('PREPARE/BOOT');
 Application.ProcessMessages;
 Form1._msg('');
 DisconnectFill;
 SetReady;
 Exit;
 end;

 if chkDOWNGRADE.Checked=True then
 begin
  if InitServiceMode then
  begin
  case PhonePresentmode of
  $01:
   begin
    if not downgradeprep
    then
    begin
     case MessageBox(0, 'Error while Downgrade Preare !!!!!!!'+#13+#10+'You can skip it and continue flashing, but phone can be damaged after.'+#13+#10+''+#13+#10+'Continue?', 'Downgrade Prepare not Done', MB_ICONWARNING or MB_YESNO) of
     idYes:
         begin
         form1._msg('Continue at user risk...');
         Application.ProcessMessages;
         end ;
     idNo:
         begin
            DisconnectFill;
            form1._msg('Break flashing on Downgrade error');
            _msg('');
            Application.ProcessMessages;
            SetReady;
            Exit;
         end;
     end;

    end;
   end;
  end;
  end
  else
  begin
     case MessageBox(0, 'Error while Downgrade Preare !!!!!!!'+#13+#10+'You can skip it and continue flashing, but phone can be damaged after.'+#13+#10+''+#13+#10+'Continue?', 'Downgrade Prepare not Done', MB_ICONWARNING or MB_YESNO) of
     idYes:
         begin
         form1._msg('Continue at user risk...');
         Application.ProcessMessages;
         end ;
     idNo:
         begin
            DisconnectFill;
            form1._msg('Break flashing on Downgrade error');
            _msg('');
            Application.ProcessMessages;
            SetReady;
            Exit;
         end;
     end;
  end;
 end;

 if stop=True then
 begin
 dostop('BOOT');
 Application.ProcessMessages;
 Form1._msg('');
 DisconnectFill;
 SetReady;
 Exit;
 end;

 btnFLASH.enabled:=True;
 BUsCheck;

 if stop=True then
 begin
 dostop('BOOT');
 Application.ProcessMessages;
 Form1._msg('');
 DisconnectFill;
 SetReady;
 Exit;
 end;
 
 if boot_done=true then
 begin
  btnFLASH.enabled:=True;
  if (chkMCUen.checked=true) and (core<>'') then
  begin
   if not UFSprepareForFlash(core) then
   begin
   form1._msg('Error... :(');
   Form1._msg('');
   DisconnectFill;
   SetReady;
   Exit;
   end;
  _msg('');
  form1.pb1.progress:=0;
  Application.ProcessMessages;
  if UFSfinishsession<>0 then exit;
  //UFSfinishsession;
  //if apeexist then if not UFSEBLockAPE then form1._msg('Error close APE');
  //UFSeblock;
  _msg('');
  end;
   if (chkPPMe.checked=true) and (ppm<>'') then
   begin
    if not UFSprepareForFlash(ppm)
    then
    begin
    form1._msg('Error... :(');
    Form1._msg('');
    DisconnectFill;
    SetReady;
    Exit;
    end;
    _msg('');
    form1.pb1.progress:=0;
    Application.ProcessMessages;
    if UFSfinishsession<>0 then exit;
   // UFSfinishsession ;
   // if apeexist then if not UFSEBLockAPE then form1._msg('Error close APE');
    //UFSeblock;
    _msg('');
   end;

   if (chkPPM1e.checked=true) and (ppm1<>'') then
   begin
    if not UFSprepareForFlash(ppm1)
    then
    begin
    form1._msg('Error... :(');
    Form1._msg('');
    DisconnectFill;
    SetReady;
    Exit;
    end;
    _msg('');
    form1.pb1.progress:=0;
    Application.ProcessMessages;
    if UFSfinishsession<>0 then exit;
   // UFSfinishsession;
   // if apeexist then if not UFSEBLockAPE then form1._msg('Error close APE');
   // UFSeblock;
    _msg('');
    end;

   if (chkCNTe.checked=true) and (image<>'') then
   begin
    if getcntsize(flicven)=128 then
    begin
     if FileExists(image+'_128') then
     begin
     Form1._msg('CNT : Converted to 128k page data exist');
     image:=image+'_128';
     end
     else
     begin
     b:=convertimages40(image);
     if b=True then image:=image+'_128';
     end;
    end;
    if not UFSprepareForFlash(image)
    then
    begin
    form1._msg('Error... :(');
    Form1._msg('');
    DisconnectFill;
    SetReady;
    Exit;
    end;
    _msg('');
    form1.pb1.progress:=0;
    Application.ProcessMessages;
    if UFSfinishsession<>0 then exit;
   //UFSfinishsession;
   //if apeexist then if not UFSEBLockAPE then form1._msg('Error close APE');
   //UFSeblock;
   _msg('');
   end;

   if (chkAPEe.checked=true) and (ape<>'') then
   begin
    if not UFSprepareForFlash(ape)
    then
    begin
    form1._msg('Error... :(');
    Form1._msg('');
    DisconnectFill;
    SetReady;
    Exit;
    end;
    _msg('');
    form1.pb1.progress:=0;
    Application.ProcessMessages;
    if UFSfinishsession<>0 then exit;
   //UFSfinishsession;
   //if apeexist then if not UFSEBLockAPE then form1._msg('Error close APE');
   //UFSeblock;
   _msg('');
   end;


    if (chkCNT3.checked=true) and (cnt3<>'') then
   begin
    if not UFSprepareForFlash(cnt3)
    then
    begin
    form1._msg('Error... :(');
    Form1._msg('');
    DisconnectFill;
    SetReady;
    Exit;
    end;
    _msg('');
    form1.pb1.progress:=0;
    Application.ProcessMessages;
    if UFSfinishsession<>0 then exit;
   //UFSfinishsession;
   //if apeexist then if not UFSEBLockAPE then form1._msg('Error close APE');
   //UFSeblock;
   _msg('');
   end;


  UFSfinishsession ;
  if apeexist then if not UFSEBLockAPE then form1._msg('Error close APE');
  UFSeblock;

  if  InitServiceMode then
  afterFlashdo
  else _msg('Init Service mode Failed! Skip AfterFlash :(');

 end;
  DisconnectFill;
  SetReady;
end;


procedure TForm1.rbCertWriteClick(Sender: TObject);
begin
  btnWriteRPL.Caption:='Write RPL';
  chkWrKeyAll.Enabled:=true;
  chkWrKeyAll.Checked:=False;
  chkSimlock.Checked:=false;
  chkSimlock.enabled:=true;
  chkSD.checked:=false;
  chkSD.enabled:=true;
  chkStufCert.enabled:=true;
  chkstufCert.checked:=false;
  chkCLMA.Enabled:=True;
  chkCLMA.Checked:=False;
end;

procedure TForm1.rbCrtEraseClick(Sender: TObject);
begin
  btnWriteRPL.Caption:='Erase CRT';
  chkWrKeyAll.Enabled:=false;
  chkWrKeyAll.Checked:=False;
  chkSimlock.Checked:=false;
  chkSimlock.enabled:=false;
  chkSD.checked:=false;
  chkSD.enabled:=false;
  chkStufCert.enabled:=False;
  chkstufCert.checked:=false;
  chkCLMA.Enabled:=false;
  chkCLMA.Checked:=False;
end;

procedure TForm1.btnRdMessClick(Sender: TObject);
var
  sec:string;
begin

  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
setbuzy;
 {btnRdMess.Enabled:=false;
 btnWriteMessg.Enabled:=false;  }
 pb1.Progress:=0;
  with SaveDialog do begin
            Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
            +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
            -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
            -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
            FilterIndex:=1;
            FileName :=StatusBar.Panels.Items[0].Text+'_'+RightFilename(StatusBar.Panels.Items[2].Text);
            InitialDir := '.\';
            DefaultExt := '.txt';
             Filter := 'Series40SMS(*.smspkg)|*.smspkg';
            FilterIndex:=1;
            Title:='Save SMS  to ...';
  end;
  if SaveDialog.Execute then begin
 if ScanProcess then begin Application.Terminate; exit; end;
 try
 if not s40drvscan then ReadDataType('SMSPackage','C:/PredefMessages/',SaveDialog.FileName)
 else ReadDataType('SMSPackage','S:/PredefMessages/',SaveDialog.FileName)
 except
 _msg('Error when read :( Try again');
 _msg('');
 end;

 end;
 {btnRdMess.Enabled:=true;
 btnWriteMessg.Enabled:=true; }
 //Form1._msg(SetReady);
 Form1.pb1.Progress:=0;
 Form1.pb1.MaxValue:=100;
 Form1._msg('');
end;


procedure TForm1.btnCamCheckClick(Sender: TObject);
var
  cam1sw,cam1hw,cam2sw,cam2hw : string;
  cchk     : string;
  sec      : string;
begin

    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

  SetBuzy;

  cam1sw:=''; cam1hw:='';
  cam2sw:=''; cam2hw:='';
  Form1._msg('Checking Camera Configuration...');

   if (StatusBar.Panels.Items[4].Text='Test') or (statusbar.Panels.Items[4].text='Local') then begin
   _msg('Operating mode is OK, no need change...');
   Application.ProcessMessages;
   end
   else
   begin
    if  Smart then SetMode('Local') else
    if (datapos='01') or (datapos='00') then  SetMode('Local')
    else _msg('Operating mode is OK, no need change...');
   Application.ProcessMessages;
   end;
    Form1._msg('');

 Application.ProcessMessages;
 if Smart=True then begin
  cam1hw:=ChkgetCamHW(1);
 if cam1hw<>'' then
 begin
  cam1sw:=ChkgetCamSW(1);
  cam1sw:=copy(cam1sw,Length(cam1sw)-5,6);
  if cam1sw='XXXXXX' then cam1sw:=cam1sw+' [ SW damaged ]';
  Form1._msg('CAM1 HW : '+cam1hw);
  Form1._msg('CAM1 SW ver : '+cam1sw);
  //_msg('');
  //form1._msg((ExtractFilePath(Application.ExeName)+'phdata\CamConf\'+cam1hw));
  if fileexists(ExtractFilePath(Application.ExeName)+'phdata\CamConf\'+cam1hw+'.dcc')
  then
  begin
  cchk:=ExtractFilePath(Application.ExeName)+'phdata\CamConf\'+cam1hw+'.dcc';
  Form1._msg('Updating Camera #1 Configuration...');
  if UploadCamSW(cchk,1) then Form1._msg('Upload done, checking...');
  cam1sw:=ChkgetCamSW(1);
  cam1sw:=copy(cam1sw,Length(cam1sw)-5,6);
  if cam1sw='XXXXXX' then cam1sw:=cam1sw+' [ SW damaged ]';
  Form1._msg('CAM1 SW ver : '+cam1sw);
  if cam1sw<>'XXXXXX [ SW damaged ]' then Form1._msg('Configuration Ok!') else Form1._msg('Configuration fail! :(');
  form1._msg('');
  end
  else form1._msg('Configuration '+cam1hw+'.dcc not found... :(');
 end
 else form1._msg('Primary Camera #1 configuration info not exist');

  cam2hw:=ChkgetCamHW(2);

 if cam2hw<>'' then
 begin
  cam2sw:=ChkgetCamSW(2);
  cam2sw:=copy(cam2sw,Length(cam2sw)-5,6);
  if cam2sw='XXXXXX' then cam2sw:=cam2sw+' [ SW damaged ]';
  Form1._msg('CAM2 HW : '+cam2hw);
  Form1._msg('CAM2 SW ver : '+cam2sw);
  //_msg('');
  if fileexists(ExtractFilePath(Application.ExeName)+'phdata\CamConf\'+cam2hw+'.dcc')
  then
  begin
  cchk:=ExtractFilePath(Application.ExeName)+'phdata\CamConf\'+cam2hw+'.dcc';
  Form1._msg('Updating Camera #2 Configuration...');
  if UploadCamSW(cchk,2) then Form1._msg('Upload done, checking...');
  cam2sw:=ChkgetCamSW(2);
  cam2sw:=copy(cam2sw,Length(cam2sw)-5,6);
  if cam2sw='XXXXXX' then cam2sw:=cam2sw+' [ SW damaged ]';
  Form1._msg('CAM2 SW ver : '+cam2sw);
  if cam2sw<>'XXXXXX [ SW damaged ]' then Form1._msg('Configuration Ok!') else Form1._msg('Configuration fail! :(');
  form1._msg('');
  end
  else form1._msg('Configuration '+cam2hw+'.dcc not found... :(');

 end
 else form1._msg('Secondary Camera #2 configuration info not exist');
//if //UploadCamSW('C:\86L10300010406260000.dcc',1) then Form1._msg('Done :)');
 end
 else
 begin

  cam1hw:=S40ChkgetCamHW(1);
  if cam1hw<>'' then
  begin
  cam1sw:=s40ChkgetCamSW(1);
  cam1sw:=copy(cam1sw,Length(cam1sw)-5,6);
  if cam1sw='XXXXXX' then cam1sw:=cam1sw+' [ SW damaged ]';
  Form1._msg('CAM1 HW : '+cam1hw);
  Form1._msg('CAM1 SW ver : '+cam1sw);


   if fileexists(ExtractFilePath(Application.ExeName)+'phdata\CamConf\'+cam1hw+'.dcc')
   then
   begin
    cchk:=ExtractFilePath(Application.ExeName)+'phdata\CamConf\'+cam1hw+'.dcc';
    Form1._msg('Updating Camera #1 Configuration...');
    if S40UploadCamSW(cchk,1) then Form1._msg('Upload done, checking...');
    cam1sw:=S40ChkgetCamSW(1);
    cam1sw:=copy(cam1sw,Length(cam1sw)-5,6);
     if cam1sw='XXXXXX' then cam1sw:=cam1sw+' [ SW damaged ]';
     Form1._msg('CAM1 SW ver : '+cam1sw);
     if cam1sw<>'XXXXXX [ SW damaged ]' then Form1._msg('Configuration Ok!') else Form1._msg('Configuration fail! :(');
     form1._msg('');
    end
   else form1._msg('Configuration '+cam1hw+'.dcc not found... :(');
  end
  else form1._msg('Primary Camera #1 configuration info not exist');



   cam2hw:=S40ChkgetCamHW(2);

  if cam2hw<>'' then
  begin
  cam2sw:=s40ChkgetCamSW(2);
  cam2sw:=copy(cam2sw,Length(cam2sw)-5,6);
  if cam2sw='XXXXXX' then cam2sw:=cam2sw+' [ SW damaged ]';
  Form1._msg('CAM2 HW : '+cam2hw);
  Form1._msg('CAM2 SW ver : '+cam2sw);
  end
  else form1._msg('Secondary Camera #2 configuration info not exist');

 end;
    Form1._msg('');
    Form1._msg('Done!');
    Form1._msg('');
  SetReady;
end;

Procedure Tform1.writeRpl(imei:string);
var
  certname : string;
  RPLf     : SYSTEm.Text;
  i,i2     : integer;
  s        : string;
  tmnr     : string;
begin
  if (RPLRecord.npc<>'') or (RPLRecord.hwc<>'') or (RPLRecord.ccc<>'') or (RPLRecord.SIMLOCK<>'')  or  (RPLRecord.SIMLOCK_KEY<>'') or (RPLRecord.WMDRM_PD<>'')
  then
  begin
     if imei='' then
     begin
      if rplrecord.npc<>'' then
      begin
      i:=Pos('47534D',rplrecord.npc);
      s:=Copy(rplrecord.npc,i+16,16);
      imei:=copy(swapstring(s),2,15);
      end
      else
         begin
         DateTimeToString(tmnr,'DD_MM_YYYY_HH',now);
         imei:=tmnr;
         end;
     end;

     if (RPLRecord.SIMLOCK='')  and  (RPLRecord.SIMLOCK_KEY='') and (RPLRecord.WMDRM_PD='') then
      begin
      certname:=GetCurrentDir+'\Backup\Cert\'+rightfilename(imei)+'_CRT.rpl';
      if fileexists(certname) then certname:=GetCurrentDir+'\Backup\Cert\'+rightfilename(imei)+'_CRT_2nd.rpl';
      end
     else
     if  (RPLRecord.npc='') and (RPLRecord.hwc='') and (RPLRecord.ccc='') then
      begin
      certname:=GetCurrentDir+'\Backup\Cert\'+rightfilename(imei)+'_SIM.rpl';
      if fileexists(certname) then certname:=GetCurrentDir+'\Backup\Cert\'+rightfilename(imei)+'_SIM_2nd.rpl';
      end
     else
     begin
     certname:=GetCurrentDir+'\Backup\Cert\'+rightfilename(imei)+'.rpl';
     if fileexists(certname) then certname:=GetCurrentDir+'\Backup\Cert\'+rightfilename(imei)+'_2nd.rpl';
     end;
      System.Assign (rplf , certname ) ;
      System.Rewrite ( rplf );
      System.writeln(rplf,'[CERT_PROG_DATA_OUT_CMT]');

     if RPLRecord.npc<>'' then
     begin
     form1._msg('NPC Certificate saved...');
     i:=0;
     i2:=1;
     s:='';
     repeat
     s:=Copy(RPLRecord.npc,i2,80);
     if (s='') then break;
     System.writeln(rplf,'NPC_DATA_'+inttostr(i+1)+'='+s);
     i2:=i2+80;
     Inc(i);
     Application.ProcessMessages;
     until (s='');
     end;

     if RPLRecord.ccc<>'' then
     begin
     form1._msg('CCC Certificate saved...');
     i:=0;
     i2:=1;
     s:='';
     repeat
     s:=Copy(RPLRecord.ccc,i2,80);
     if (s='') then break;
     System.writeln(rplf,'CCC_DATA_'+inttostr(i+1)+'='+s);
     i2:=i2+80;
     Inc(i);
     Application.ProcessMessages;
     until (s='');
     end;

     if RPLRecord.hwc<>'' then
     begin
     form1._msg('HWC Certificate saved...');
     i:=0;
     i2:=1;
     s:='';
     repeat
     s:=Copy(RPLRecord.hwc,i2,80);
     if (s='') then break;
     System.writeln(rplf,'HWC_DATA_'+inttostr(i+1)+'='+s);
     i2:=i2+80;
     Inc(i);
     Application.ProcessMessages;
     until (s='');
     end;

     if (RPLRecord.SIMLOCK<>'') and (length(RPLRecord.SIMLOCK)>80) then
     begin
     form1._msg('SimLock Data saved...');
     i:=0;
     i2:=1;
     s:='';
     repeat
     s:=Copy(RPLRecord.SIMLOCK,i2,80);
     if (s='') then break;
     System.writeln(rplf,'SIMLOCK_DATA_'+inttostr(i+1)+'='+s);
     i2:=i2+80;
     Inc(i);
     Application.ProcessMessages;
     until (s='');
     end;
      if RPLRecord.SIMLOCK_KEY<>'' then
     begin
       form1._msg('SimLock Key saved...');
     i:=0;
     i2:=1;
     s:='';
     repeat
     s:=Copy(RPLRecord.SIMLOCK_KEY,i2,80);
     if (s='') then break;
     System.writeln(rplf,'SIMLOCK_KEY_DATA_'+inttostr(i+1)+'='+s);
     i2:=i2+80;
     Inc(i);
     Application.ProcessMessages;
     until (s='');
     end;
      if RPLRecord.WMDRM_PD<>'' then
     begin
      form1._msg('WMDRM_PD Data saved...');
     i:=0;
     i2:=1;
     s:='';
     repeat
     s:=Copy(RPLRecord.WMDRM_PD,i2,80);
     if (s='') then break;
     System.writeln(rplf,'WMDRM_PD_DATA_'+inttostr(i+1)+'='+s);
     i2:=i2+80;
     Inc(i);
     Application.ProcessMessages;
     until (s='');
     end;
     System.Close(rplf);
     Form1._msg('');
     Form1._msg('RPL saved : '+certname);
     RPLRClear;
     Form1._msg('');
  end;
end;

procedure TForm1.btnFormatS40LowLevelClick(Sender: TObject);
var
  erasearea : string;
  s         : string;
  x         : Integer;
  b         : Boolean;
begin

  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    s:=CardPass(crpass);
    if s <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}


 erasearea:='';
 if cbbLFmdel.text='Select Model' then Exit; // '0000000000000000';    SAFE AREAS (USER PM) // RM, model
 if cbbLFmdel.text='RM-233, 8800a' then erasearea:='01EC000003F9FFFF';//01BC0000 01EBFFFF // RM-233, 8800a
 if cbbLFmdel.text='RM-242, 5610' then  erasearea:='01FC000003F9FFFF';//01BC0000 01FBFFFF // RM-242, 5610
 if cbbLFmdel.text='RM-249, 7500' then  erasearea:='0190000003FBFFFF';//01780000 018FFFFF // RM-249, 7500
 if cbbLFmdel.text='RM-264, 7900' then  erasearea:='01EC000003F9FFFF';
 if cbbLFmdel.text='RM-271, 6555' then  erasearea:='01FC000003F9FFFF';//01BC0000 01FBFFFF // RM-271, 6555
 if cbbLFmdel.text='RM-325, 6600f' then erasearea:='0266000003F9FFFF';
 if cbbLFmdel.text='RM-352, 3600s' then erasearea:='022C000003FBFFFF';//01F20000 022BFFFF // RM-352, 3600s
 if cbbLFmdel.text='RM-354, 7610s' then erasearea:='022C000003FBFFFF';//01F20000 022BFFFF // RM-354, 7610s
 if cbbLFmdel.text='RM-364, 3120c' then erasearea:='01FC000003F9FFFF';//01CC0000 01FBFFFF // RM-364, 3120
 if cbbLFmdel.text='RM-398, 7510s' then erasearea:='0298000003FBFFFF';//025E0000 0297FFFF // RM-398, 7510a
 if cbbLFmdel.text='RM-411, 5220' then  erasearea:='0216000003FBFFFF';//01DC0000 0215FFFF // RM-411, 5220
 if cbbLFmdel.text='RM-414, 6600s' then erasearea:='0262000003F9FFFF';//021C0000 0261FFFF // RM-414, 6600s
 if cbbLFmdel.text='RM-429, 3610f' then erasearea:='01FC000003F9FFFF';//01BC0000 01FBFFFF // RM-429, 3610f
 if cbbLFmdel.text='RM-436, 7210s' then erasearea:='01F8000003FBFFFF';//01BE0000 01F7FFFF // RM-436, 7210
 if cbbLFmdel.text='RM-443, 6303c' then erasearea:='029C000003FBFFFF';//02620000 029BFFFF // RM-443, 6303c
 if cbbLFmdel.text='RM-495, 5130' then  erasearea:='0216000003FBFFFF';//01DC0000 0215FFFF // RM-495, 5130XM
 if cbbLFmdel.text='RM-518, 3720c' then erasearea:='027C000003FBFFFF';//02420000 027BFFFF // RM-518, 3720c
 if cbbLFmdel.text='RM-561, 2700c' then erasearea:='0216000003FBFFFF';//01DC0000 0215FFFF // RM-561, 2700c
 if cbbLFmdel.text='RM-570, 6600i' then erasearea:='0262000003F9FFFF';//021C0000 0261FFFF // RM-570, 6600i
 if cbbLFmdel.text='RM-578, 2730' then  erasearea:='0246000003FBFFFF';//01DC0000 0215FFFF // RM-578, 2730
 if cbbLFmdel.text='RM-635, 2690' then  erasearea:='0216000003FBFFFF';//02160000 03FBFFFF // RM-635, 2690


 if erasearea='' then Exit;

 case MessageBox(0, 'WARNING! '+#13+#10+'USE That Option ONLY for CORRECT model, otherwise phone can be fully DAMAGED!'+#13+#10+'USE That option ONLY, if phone HANG on Nokia LOGO and You sure - it is NOT HW'+#13+#10+'BEFORE USE that - TRY Flash MCU+PPM'+#13+#10+'THAT option WILL KILL User Gallery, but can Save PhoneBook.', 'Think, before do...', MB_ICONWARNING or MB_OKCANCEL) of
  idOk: Application.ProcessMessages;
  idCancel: Exit ;
 end;

 x:=0;
 SetBuzy;
 if ConMode=1 then DisUfsButton;
 case ConMode of
  1:
  begin
     if fbdev=1 then
     begin
      case PhonePresentmode of
       $00:
       begin
        form1._msg('User confirm Format');
        BUsCheckCMTonly;
        if boot_done then
        begin
         if not UFSFormatLow(erasearea) then
         begin
          Form1._msg('Error while formatting... Break format... :(');
          form1._msg('');
          form1.pb1.progress:=0;
          SetReady;
          Exit;
         end;

        end
        else
        begin
         Form1._msg('Error booting phone... Break format... :(');
         form1._msg('');
         SetReady;
         Exit;
         end;
        form1._msg('UserArea format done');
        form1._msg('');
        form1.pb1.progress:=0;
        end;
       $01:
        begin
        Form1._msg('Phone Alive! Not need format!');
        form1._msg('');
        SetReady;
        Exit;
        end;
      end;
     end
     else
     begin
     Form1._msg('Need use FlashBus interface...');
     form1._msg('');
     SetReady;
     Exit;
     end;
     form1.pb1.progress:=0;
  end;
  0:
  begin
   case PhonePresentmode of
   $00:
    begin
     //form1._msg(erasearea);
      if core<>'' then
      begin
      x:=BB5ScanHeader(core);
       if x<>1 then
       begin
       Form1._msg('Selected Incorrect MCU file, it must BE SAME, as selected model');
       form1._msg('');
       SetReady;
       Exit;
       end;
       setbuzy;
       b:=BB5_DEADFlashing(1);
       if b=True then
       begin
        b:=BB5_EraseCustomArea_USB(erasearea);
        if b<>true then Exit;
        form1._msg('UserArea format done');
        form1._msg('');
        form1.pb1.progress:=0;
        Setready;
       end
       else Exit;

      end
      else
      begin
       Form1._msg('Select MCU file, it must BE SAME, as selected model');
       form1._msg('');
       SetReady;
       Exit;
      end;
    end;
   $01:
    begin
     Form1._msg('Phone Alive! Not need format!');
     form1._msg('');
     SetReady;
     Exit;
    end;
   end;
  end;
 end;
 SetReady;
end;

procedure Tform1.DisUfsButton();
begin
  Application.ProcessMessages;
  checkbtn.enabled:=False;
  btnReadRPL.enabled:=False;
  btnWriteRPL.Enabled:=False;
  btnFLASH.Enabled:=False;
  btnFormatS40LowLevel.Enabled:=False;
  Application.ProcessMessages;
end;

procedure Tform1.EnUfsbutton();
begin
  checkbtn.enabled:=True;
  btnReadRPL.enabled:=True;
  btnWriteRPL.Enabled:=True;
  btnFLASH.Enabled:=true;
  btnFormatS40LowLevel.Enabled:=True;
end;

procedure TForm1.btnReadCamConfClick(Sender: TObject);
var
  cam1sw,cam1hw,cam2sw,cam2hw : string;
  cchk     : string;
  sec      : string;
  s1, s2   : WideString;
begin

    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  form1._msg('Try Read Camera Configuration to base...');
  Form1._msg('');
   s1:=PmReadRecord(355,0);
   s2:=PmReadRecord(355,1);
   if (s1<>'') or (s1<>'Error') then
   begin
   parsecamconf(s1);
   end
   else Form1._msg('Cam 1 configuration not found');
   Form1._msg('');
   Application.ProcessMessages;
   if (s2<>'') or (s2<>'Error') then
   begin
   parsecamconf(s2);
   end
   else Form1._msg('Cam 2 configuration not found');
   Form1._msg('');
   Form1._msg('Done!');
   Form1._msg('');
   SetReady;
end;

procedure TForm1.btnInfineOnParseClick(Sender: TObject);
var
  outBlock,verinfoblock : TMemoryStream;
  i : integer;
  eraseInfo : TStringList;
begin
 { i:=StrToInt(edtModeParse.Text);
  if core<>'' then
  begin
   outBlock:=TMemoryStream.create;
   VerinfoBlock:=TMemoryStream.create;
   if ParseInfineon(core,i,outBlock) then
     begin
     outBlock.SaveToFile('C:\Extracted_mode_'+edtModeParse.Text);
      if i=3 then
      begin
      eraseInfo:=TStringList.Create;
      GetEraseBlk(outBlock,eraseinfo);
      for i:=0 to eraseInfo.count-1 do Form1._msg(eraseInfo.Strings[i]);
      end;
     outBlock.free;
     ParseInfineon(core,0,verinfoBlock);
     Form1._msg(getFwinfo(verinfoBlock));
     end
   else form1._msg('Error :(');
  end;   }

end;

procedure TForm1.btnBinfClick(Sender: TObject);
begin
setbuzy;
//Boot_infineon;
 
end;

procedure TForm1.cbbModeFlashChange(Sender: TObject);
begin
  FselectFlashMode;
end;

procedure TForm1.FselectFlashMode();
begin
 case cbbModeFlash.ItemIndex of
 0:
  begin
  Application.ProcessMessages;   // manual
  exit;
  end;
 1:  // full
  begin
   if MCUt.Text<>'' then chkMCUen.checked:=True;
   if PPMt.Text<>'' then chkPPMe.Checked:=True;
   if PPM1t.Text<>'' then chkPPM1e.checked:=True;
   if CNTt.text<>'' then chkCNTe.checked:=True;
   if APEt.Text<>'' then chkAPEe.checked:=True;
   if Cnt3t.text<>'' then chkCnt3.checked:=True;
   chkAFFset.checked:=True;
   chkCheckRead.checked:=True;
   chkChPC.checked:=True;
   chkBootNormal.checked:=True;
   Exit;
  end;
 2:    //safe
  begin
   if MCUt.text<>'' then chkMCUen.checked:=true;
   if PPMt.Text<>'' then chkPPMe.Checked:=true;
   //chkPPM1e.checked:=false;

   if PPM1t.text<>'' then
   begin
   if (Pos('ENO',PPM1t.text)<>0) or (Pos('APEONLY',PPM1t.text)<>0) or (Pos('APE_ONLY', PPM1t.text)<>0) or ((Pos('erase_', PPM1t.text)<>0) and (Pos('drive', PPM1t.text)<>0)) then   chkPPM1e.checked:=True else
   chkppm1e.checked:=false;
   end;
   if CNTt.text<>'' then
   begin
   if (Pos('ENO',CNTt.text)<>0) or (Pos('APEONLY',Cntt.text)<>0) or (Pos('APE_ONLY',Cntt.text)<>0) or ((Pos('erase_',cntt.text)<>0) and (Pos('drive',cntt.text)<>0)) then  chkCNTe.checked:=True else
   chkCNTe.checked:=false;
   end;
   if APEt.text<>'' then
   begin
   if (Pos('ENO',APEt.text)<>0) or (Pos('APEONLY',apet.text)<>0) or (Pos('APE_ONLY',apet.text)<>0) or ((Pos('erase_',APEt.text)<>0) and (Pos('drive',APEt.text)<>0)) then  chkAPEe.checked:=True else
   chkapee.checked:=false;
   end;
   if Cnt3t.text<>'' then
   begin
   if (Pos('ENO',Cnt3t.text)<>0) or (Pos('APEONLY',Cnt3t.text)<>0) or (Pos('APE_ONLY',Cnt3t.text)<>0) or ((Pos('erase_',Cnt3t.text)<>0) and (Pos('drive',Cnt3t.text)<>0)) then  chkCnt3.checked:=True else
   chkCnt3.checked:=false;
   end;
   chkAFFset.checked:=false;
   chkCheckRead.checked:=true;
   chkChPC.checked:=false;
   chkBootNormal.checked:=false;
   chkReseLT.Checked:=false;
   Exit;
  end;
 3:   // PPM
  begin
   chkMCUen.checked:=false;
   if PPMt.Text<>'' then chkPPMe.Checked:=true;
   chkPPM1e.checked:=false;
   chkCNTe.checked:=false;
   chkAPEe.checked:=false;
   chkCnt3.checked:=false;
   chkAFFset.checked:=false;
   chkCheckRead.checked:=false;
   chkChPC.checked:=false;
   chkBootNormal.checked:=false;
   chkReseLT.Checked:=false;
   exit;
  end;
 4:   // Dead-test
  begin
    case ConMode of
    $00:
    begin
    chkMCUen.checked:=false;
    chkPPMe.Checked:=false;
    chkPPM1e.checked:=false;
    chkCNTe.checked:=false;
    chkAPEe.checked:=false;
    chkCnt3.checked:=false;
    chkAFFset.checked:=false;
    chkCheckRead.checked:=false;
    chkChPC.checked:=false;
    chkBootNormal.checked:=false;
    chkReseLT.Checked:=false;
    case PhonePresentmode of
    $00:
    begin
    chkDEADMODE.Checked:=true;
     if chkDEADMODE.Checked=true then
     begin
          Setbuzy;
          btnFLASH.Enabled:=True;
          chkDOWNGRADE.Enabled:=false;
          Form1.StatusBar.Panels.Items[6].Text :='DEAD';
     end;
    end;
    $01 : Application.ProcessMessages;
    end;
    Exit;
    end;


   $01: begin
        cbbModeFlash.ItemIndex:=0;
        exit;
        end;

   end;
  end;
 end;
end;

procedure TForm1.PPMtClick(Sender: TObject);
begin
 if ppmlang<>'' then ShowMessage(ppmlang);
end;


procedure TForm1.PPM1tClick(Sender: TObject);
begin
   if ppm1lang<>'' then ShowMessage(ppm1lang);
end;

procedure TForm1.SlxUClick(Sender: TObject);
var
sec: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Unlock procedure started...');
  _msg('');
      if DoSLUnlock then _msg('Done!') else _msg('Unlock Error!');;
  _msg('');
   SetReady;

end;

procedure TForm1.ChUnlClick(Sender: TObject);
var
sec: string;
i:integer;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
    i:=CheckServerUser ;
    if i=-1 then begin
    _msg('Error in job...');
    _msg('');
    SetReady;
    exit;
    end;
  if StatusBar.Panels.Items[3].Text <>'Disconnected' then begin
  _msg('Unlock procedure started...');
  _msg('');
      if DoChUnlock then _msg('Done!') else _msg('Unlock Error!');;
  _msg('');
  end else _msg('Phone not connected...');
   SetReady;
end;

procedure TForm1.LsxBClick(Sender: TObject);
var
sec: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Local SX4 procedure started...');
  _msg('');
      if DoSX4 then _msg('Done!');
   _msg('');
   SetReady;
end;

procedure TForm1.UplJClick(Sender: TObject);
var
lf:TIniFile;
sec,hashs: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Upload Job procedure started...');
  _msg('');
  if StatusBar.Panels.Items[3].Text ='Disconnected' then begin
  _msg('Phone not connected... Try upload job from log file...');
   case MessageBox(0, 'Do You want upload job'+#13+#10+'           from file ?'+#13+#10+''+#13+#10+'No -  abort operations...', 'UPLOAD JOB', MB_ICONWARNING or MB_YESNO) of
    idYes :
     begin
      with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := StartDir+'Local_calc\';
       DefaultExt := 'bcl';
       Filter := 'log files (*.bcl)|*.bcl';
       Title:='Open Log file ';
      end;
    if OpenDialog.Execute then begin
      lf:=TIniFile.Create(OpenDialog.FileName);
      imei_s:=lf.ReadString('Log','imei','');
      hashs:=lf.ReadString('Log','hash','');
      code_s:=lf.ReadString('Log','code','');
      lf.Free;
      if ((imei_s<>'') and (hashs<>'')) then begin
        if DoUplJobFile(imei_s,hashs,code_s) then _msg('Done!') else _msg('Upload Job fail...!');
     _msg('');
      SetReady;
     Application.ProcessMessages;
     exit;
      end else begin
     _msg('Load from file error... Bad file... :(');
     _msg('');
      SetReady;
     Application.ProcessMessages;
     exit;
      end;
     end else begin
     _msg('Aborted by user...');
     _msg('');
      SetReady;
     Application.ProcessMessages;
     exit;
     end;
     end;
    idNo  :
    begin
     _msg('Aborted by user...');
     _msg('');
      SetReady;
     Application.ProcessMessages;
     exit;
    end;
   end;
   end else if DoSLUnlock then _msg('Done!') else _msg('Upload Job fail...!');
  _msg('');
   SetReady;
end;


procedure TForm1.CncJClick(Sender: TObject);
var
sec: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Cancel Job procedure started...');
  _msg('');
      if DoCancelJob then _msg('Done!') else _msg('Cancel Job fail...!');;
  _msg('');
   SetReady;

end;

procedure TForm1.chkWrKeyAllClick(Sender: TObject);
begin
  if chkWrKeyAll.checked=true then
  begin
  chkCLMA.checked:=True;
  chkStufCert.checked:=True;
  chkSD.checked:=True;
  chkSimlock.checked:=True;
  chkErNPC.checked:=True;
  chkErCC.checked:=True;
  chkerHWC.checked:=True;
  chkCLMA.Enabled:=false;
  chkStufCert.Enabled:=false;
  chkSD.Enabled:=false;
  chkSimlock.Enabled:=false;
  chkErNPC.Enabled:=false;
  chkErCC.Enabled:=false;
  chkerHWC.Enabled:=false;
  Exit;
  end
  else
  begin
  chkCLMA.Enabled:=True;
  chkStufCert.Enabled:=True;
  chkSD.Enabled:=True;
  chkSimlock.Enabled:=True;
  chkErNPC.Enabled:=True;
  chkErCC.Enabled:=True;
  chkerHWC.Enabled:=True;
  Exit;
  end;
end;

procedure TForm1.RSDDClick(Sender: TObject);
var
sec: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Repair SD procedure started...');
  _msg('');
      if DoRepSDD then _msg('Done!') else _msg('Repair fail...!');;
  _msg('');
   SetReady;
end;

procedure TForm1.RdUniKeyClick(Sender: TObject);
var
sec: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Read Uniq key data started...');
  _msg('');
      if DoReadKey then _msg('Done!') else _msg('Read fail...!');;
  _msg('');
   SetReady;

end;

procedure TForm1.btnSx4UplTuneClick(Sender: TObject);
var
sec: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  form1._msg('Uploading RF/Battery tune to phone...');
  if not uploadtunesx then
  begin
  Form1._msg('Upload failed');
  form1._msg('');
  SetReady;
  end;
end;


procedure TForm1.btnReadPPMcatClick(Sender: TObject);
var
  i,j:integer;
  adrr : integer;
  datastream : TMemoryStream;
  bres:Boolean;
begin
 setbuzy;
 if not Boot_infineon then
 begin
 Form1._msg('Boot failed, phone not found');
 Form1._msg('');
 SetReady;
 exit;
 end;
 if not halfboot then
 begin
 form1._msg('Error booting phone...');
 form1._msg('');
 SetReady;
 Exit;
 end;
 SetBuzy;
 Form1._msg('PSI : '+psi);
 Form1._msg('Trying dump eeprom....');
 datastream:=TMemoryStream.Create;
 dumpppmcatalog($790000,$800000,datastream);
 datastream.Seek(0,soFromBeginning);
 i:=0;
 i:=datastream.Size;
 datastream.SaveToFile('C:\epppmm.bin');
 if datastream.size>$100 then Form1._msg('Done! '+inttostr(i)+' bytes readed')
 else Form1._msg('Error! required data not found! :(');
 datastream.Free;
 form1._msg('');
 SetReady;
end;

procedure TForm1.btnRdFeppClick(Sender: TObject);
var
  i,j:integer;
  adrr : integer;
  datastream : TMemoryStream;
begin
 setbuzy;
 if not Boot_infineon then
 begin
 Form1._msg('Boot failed, phone not found');
 Form1._msg('');
 SetReady;
 exit;
 end;
 if not halfboot then
 begin
 form1._msg('Error booting phone...');
 form1._msg('');
 SetReady;
 Exit;
 end;
 SetBuzy;
 Form1._msg('Trying dump eeprom....');
 datastream:=TMemoryStream.Create;
 dumpregionepp($790000,$800000,datastream);
 datastream.Seek(0,soFromBeginning);
 i:=0;
 i:=datastream.Size;
 datastream.SaveToFile('C:\eppreaded.bin');
 datastream.Free;
 Form1._msg('Done! '+inttostr(i)+' bytes readed');
 SetReady;
 Form1._msg('');
end;

procedure TForm1.btnWriteMsgClick(Sender: TObject);
var
  sec:string;
  suc : Boolean;
  F:TFileStream;
  ds:TMemoryStream;
begin

  {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}

   with OpenDialog do begin
       Options:=Options+[ofFileMustExist]-[ofHideReadOnly]
        +[ofNoChangeDir]-[ofNoLongNames]-[ofNoNetworkButton]-[ofHideReadOnly]
        -[ofOldStyleDialog]+[ofOverwritePrompt]+[ofPathMustExist]
        -[ofReadOnly]-[ofShareAware]-[ofShowHelp];
       FilterIndex:=1;
       FileName :='';
       InitialDir := '.\';
       DefaultExt := '.smspkg';
        Filter := 'Series40SMS(*.smspkg)|*.smspkg';
        FilterIndex:=1;
       Title:='Open SMS pack file for write ...';
       end;
      if OpenDialog.Execute then
      begin
          SetBuzy;
           {btnRdMess.Enabled:=false;
           btnWriteMessg.Enabled:=false; }
          _msg('Restoring UserData : [SMS Package]');
          _msg('Generation mode    : [S40]');
          if ScanProcess then begin Application.Terminate; exit; end;
          F:=TFileStream.Create(OpenDialog.filename,fmOpenRead);
          ds:=TMemoryStream.Create;
          DecryptF(F,ds,fullid);
          f.Free;
          if MyImageWriter(ds)=true then
          begin
          form1._msg('SMS Package restored');
          _msg('');
          form1._msg('-> Restart phone for accept changes');
          form1._msg('-> Phone can freeze first 5 minutes');
          _msg('');
          _msg('Done!');
          end
          else Form1._msg('Error while restore...');
          //_msg('Done');
          ds.free;
          setready;
           Form1.pb1.Progress:=0;
           Form1.pb1.MaxValue:=100;
          _msg('');
      end
      else Exit;
end;



procedure TForm1.btn333Click(Sender: TObject);
begin
Form1._msg(getversion(core));
end;

procedure TForm1.RepSLbClick(Sender: TObject);
var
sec: string;
begin
    {$I VM_Start.inc}
//  {$I crypt_start.inc}
    if not connect then begin Application.Terminate; exit; end;
    sec:=CardPass(crpass);
    if sec <> fullid then begin Application.Terminate; exit; end;
    if ScanProcess then begin Application.Terminate; exit; end;
//    {$I crypt_end.inc}
  {$I VM_End.inc}
  SetBuzy;
  _msg('Repair SL procedure started...');
  _msg('');
      if DoRepSL then _msg('Done!') else _msg('Repair fail...!');;
  _msg('');
   SetReady;
end;

procedure TForm1.InfLockInfineon();
var
ig:TIniFile;
s,pr:string;
i,j,k,bl,re,z:integer;
begin
    s:=FbusGetSlInfo;
//    _msg(s);
    if s<>'Error' then begin
    pr:=Copy(s,21,8);
    ig:=TIniFile.Create(ExtractFileDir(Application.ExeName)+'\providers.ini');
    _msg('Sl Conf  - '+Copy(s,21,3)+'-'+Copy(s,24,2)+'-'+Copy(s,26,11));
    _msg('Sl Prof  - '+Copy(s,37,15)+'-'+Copy(s,52,1));
    _msg('Sl Aux   - '+Copy(s,53,8));
    _msg('Hw Sig   - '+Copy(s,61,16));
    _msg('Provider - '+ig.ReadString('Providers',pr,'Unknown providers'));
    ig.Free;
    if s<>'Error' then begin
    s:=FbusGetSlStat;
    _msg('Lock info:');
    StrToBufHex(s,@tmarray[0]);
    bl:=tmarray[22];
    z:=bl shl 3;
    i:=26;
    for k:=1 to bl do begin
     _msg('Blok '+IntToStr(k));
     re:=tmarray[i+(k shl 3)-4];
     s:='';
     for j:=1 to re do begin
     s:=s+'L'+IntToStr(j)+' - ';
     if tmarray[i+z+(j*20)-1]=3 then s:=s+'Open;  ' else s:=s+'Close;  ';
     end;
     _msg(s);
    end;
    end else _msg('LockStatus read error...');
    end else _msg('SimLock read error...');
    _msg('');

end;

end.

