{DivFix is a utility for reindexing partial DivX AVI movies
Copyright (C) 2000-2003  Csaba Budai

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

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

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

unit DivX;
{$DEFINE WINDOWS}

interface

uses
  SysUtils, Classes,
{$IFDEF WINDOWS}
  Windows, Messages, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, Menus,
  ExtCtrls, Buttons, DropSource, DropTarget,ComCtrls, OleCtnrs, ShellApi, FileCtrl;
{$ELSE}
  QStdCtrls, QForms, QExtCtrls, QControls, QComCtrls, QGraphics, QDialogs, QTypes, Qt,
  QMenus, QMask, QButtons;
{$ENDIF}


type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    SpeedButton2: TSpeedButton;
    SpeedButton3: TSpeedButton;
    CheckBox1: TCheckBox;
    CheckBox2: TCheckBox;
    CheckBox3: TCheckBox;
    MaskEdit2: TMaskEdit;
    MaskEdit3: TMaskEdit;
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    Open1: TMenuItem;
    Rebuild1: TMenuItem;
    Strip1: TMenuItem;
    Check1: TMenuItem;
    Exit1: TMenuItem;
    Settings1: TMenuItem;
    Stayontop1: TMenuItem;
    Help1: TMenuItem;
    About1: TMenuItem;
    OpenDialog1: TOpenDialog;
    OpenDialog2: TOpenDialog;
{$IFDEF WINDOWS}
    DropFileTarget1: TDropFileTarget;
{$ENDIF}
    ProgressBar1: TProgressBar;
    Image1: TImage;
    Bevel1: TBevel;
    Button5: TButton;
    Button6: TButton;
    ListBox1: TListBox;
    Bevel2: TBevel;
    Button7: TButton;
{$IFDEF WINDOWS}
    RichEdit1: TRichEdit;
{$ELSE}
		Memo1: TMemo;
{$ENDIF}
    PopupMenu1: TPopupMenu;
    Clear1: TMenuItem;
    Autoclear1: TMenuItem;
    Autoclearlist1: TMenuItem;
    procedure SpeedButton2Click(Sender: TObject);
    procedure SpeedButton3Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Exit1Click(Sender: TObject);
    procedure About1Click(Sender: TObject);
    procedure StayTop(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
{$IFDEF WINDOWS}
    procedure DropFileTarget1Drop(Sender: TObject; ShiftState: TShiftState;
      Point: TPoint; var Effect: Integer);
{$ENDIF}
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure CheckBox1Click(Sender: TObject);
    procedure CheckBox3Click(Sender: TObject);
    procedure ShowWebPage(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure Button7Click(Sender: TObject);
    procedure Clear1Click(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure Autoclear1Click(Sender: TObject);
    procedure Autoclearlist1Click(Sender: TObject);

  private
    { Private declarations }
  public
  	Input,Output				: File;
    Backup							:	File;
    Log									:	Text;
    Config							:	Text;
		i,j									:	Cardinal;
		Size,Position				:	Cardinal;
    Scale,Rate					:	Cardinal;
		StreamStart					:	Cardinal;
    IndexStart					:	Cardinal;
    StreamSize					:	Cardinal;
    AVISize							:	Cardinal;
    Difference					:	Cardinal;
    IndexDifference			:	Cardinal;
    Frame,Time					:	Cardinal;
		LastIndexPosition		:	Cardinal;
    LastBackupPosition	:	Cardinal;
    LastFrame,LastIndex	:	Cardinal;
    Item								:	Cardinal;
    Errors							:	Cardinal;
		FrameType						:	Cardinal;
    KeyType							:	Cardinal;
    Interleaved		  	  : Boolean;
    OnTop								:	Boolean;
    StopButton					:	Boolean;
    Logging							:	Boolean;
    CommandLine					:	Boolean;
    CfgStay							:	Boolean;
    CfgClear						:	Boolean;
    CfgCList						:	Boolean;
    CfgKeep							:	Boolean;
    CfgCut							:	Boolean;
    CfgLog							:	Boolean;
		CfgDir							:	String;
    CfgDest							:	String;
    ConfigDir						:	String;
    Text,Hour,Minute		: String;
    Second							:	String;
    Text2								:	String[2];
    Codec								:	String[4];
		Chunkname						:	String[8];
		Temp								: integer;
		Buffer							:	Array [0..32800] Of Byte;
  end;

  Const
  	KeyFrame  :	Longint = 16;
    NormFrame	:	Longint = 0;
    Number		:	Set of char =['0'..'9'];

var
  Form1: TForm1;

implementation

uses About, DirRequester;

{$IFDEF WINDOWS}
{$R *.DFM}
{$ELSE}
{$R *.dfm}
{$ENDIF}

procedure DisableButtons;
begin
	Form1.File1.Enabled:=False;
	Form1.Settings1.Enabled:=False;
	Form1.Help1.Enabled:=False;
	Form1.ListBox1.Enabled:=False;
 	Form1.SpeedButton2.Enabled:=False;
 	Form1.SpeedButton3.Enabled:=False;
	Form1.MaskEdit2.Enabled:=False;
	Form1.MaskEdit3.Enabled:=False;
	Form1.Button1.Enabled:=False;
  Form1.Button2.Enabled:=False;
  Form1.Button3.Enabled:=False;
	Form1.Button5.Enabled:=False;
  Form1.Button6.Enabled:=False;
  Form1.Button7.Enabled:=False;
  Form1.CheckBox1.Enabled:=False;
  Form1.CheckBox2.Enabled:=False;
  Form1.CheckBox3.Enabled:=False;
end;

procedure EnableButtons;
begin
	Form1.File1.Enabled:=True;
	Form1.Settings1.Enabled:=True;
	Form1.Help1.Enabled:=True;
	Form1.ListBox1.Enabled:=True;
	If Form1.CheckBox1.Checked Then
  Begin
  	Form1.SpeedButton2.Enabled:=True;
	  Form1.MaskEdit2.Enabled:=True;
  End;
	If Form1.CheckBox3.Checked Then
  Begin
  	Form1.SpeedButton3.Enabled:=True;
	  Form1.MaskEdit3.Enabled:=True;
  End;
 	Form1.Button1.Enabled:=True;
  Form1.Button2.Enabled:=True;
  Form1.Button3.Enabled:=True;
 	Form1.Button5.Enabled:=True;
  Form1.Button6.Enabled:=True;
  Form1.Button7.Enabled:=True;
  Form1.CheckBox1.Enabled:=True;
  If Form1.CheckBox1.Checked Then Form1.CheckBox2.Enabled:=True;
  Form1.CheckBox3.Enabled:=True;
end;

procedure WriteOut(Text : String);
begin
	If Form1.Logging Then Writeln(Form1.Log,Text)
  Else
  Begin
{$IFDEF WINDOWS}
  	Form1.RichEdit1.Lines.Append(Text);
    Form1.RichEdit1.Perform(EM_SCROLLCARET,0,0);
{$ELSE}
  	Form1.Memo1.Lines.Append(Text);
{$ENDIF}
  End;
end;

procedure ZeroAlign(Var Text : String);
Var	i	: Integer;

begin
	For i:=1 To Length(Text) Do
  	If Text[i]=' ' Then Text[i]:='0';
end;

function CheckOtherIndex(Var Input : File) : Cardinal;
Var	Position,i	:	Cardinal;
		OldPosition	:	Cardinal;
    Buffer			:	Array [0..32800] of Byte;
    Text				:	String[2];
    Text2				:	String[4];
    Temp				:	Integer;

begin
	OldPosition:=FilePos(Input);
  Seek(Input,FileSize(Input)-32768);
  BlockRead(Input,Buffer,32768);
  Text2:='    ';
  i:=32768;
  Repeat
	  Move(Buffer[i],Text2[1],4);
    Text:=Copy(Text2,3,2);
  	Dec(i);
  Until (i<0) Or (((Text='dc') Or (Text='db') Or (Text='wb')) And ((Text2[1] In Number) And
  			(Text2[2] In Number))) Or (Text2='idx1');
  If (((Text='dc') Or (Text='db') Or (Text='wb')) And ((Text2[1] In Number) And (Text2[2] In Number))) Then
  Begin
  	Move(Buffer[i-15],Text2[1],4);
    Text:=Copy(Text2,3,2);
    If (((Text='dc') Or (Text='db') Or (Text='wb')) And ((Text2[1] In Number) And (Text2[2] In Number))) Then
    Begin
		  Position:=FileSize(Input);
		  i:=32768;
		  If Position>32768 Then
		  Repeat
				Dec(Position,32764);
		    Seek(Input,Position);
		    BlockRead(Input,Buffer,32768,Temp);
		    i:=Temp;
		    Repeat
					Dec(i);
		      Move(Buffer[i],Text2[1],4);
		    Until (i<0) Or (Text2='idx1');
			Until (Position<32768) Or (Text2='idx1');
		  If (Position<32768) And (Text2<>'idx1') Then
		  Begin
		  	i:=Position;
		    Position:=0;
		    Seek(Input,0);
		    Repeat
					Dec(i);
		      Move(Buffer[i],Text2[1],4);
		    Until (i<0) Or (Text2='idx1');
		  End;
		  Seek(Input,OldPosition);
		  If Text2='idx1' Then Result:=Position+i
		  Else Result:=0;
    End
    Else Result:=0;
  End
  Else Result:=0;
end;

procedure TForm1.SpeedButton2Click(Sender: TObject);
begin
	Form4.Left:=Form1.Left+70;
  Form4.Top:=Form1.Top-28;
  Form1.Enabled:=False;
{$IFDEF WINDOWS}
  Application.NormalizeTopMosts;
	Form4.ShowModal;
  Application.RestoreTopMosts;
	If Stayontop1.Checked Then
    SetWindowPos(TForm1(Self).Handle,HWND_TOPMOST,0,0,0,0,SWP_NOSIZE+SWP_NOMOVE);
{$ELSE}
	Form4.ShowModal;
{$ENDIF}
end;

procedure TForm1.SpeedButton3Click(Sender: TObject);
begin
	If OpenDialog2.Execute Then MaskEdit3.Text:=OpenDialog2.FileName;
end;

procedure TForm1.Button1Click(Sender: TObject);
Var k	:	Cardinal;

Label BError;
Label BStartRead;

begin
{$IFDEF WINDOWS}
	If Autoclear1.Checked Then RichEdit1.Clear;
{$ELSE}
	If Autoclear1.Checked Then Memo1.Clear;
{$ENDIF}
	Logging:=False;
	DisableButtons;
	If ListBox1.Items.Count=0 Then
  Begin
		WriteOut(' No file selected.');
    EnableButtons;
  	Exit;
  End
  Else
  Begin
   	i:=0;
	  While i<=ListBox1.Items.Count-1 Do
    Begin
{$IFDEF WINDOWS}
			ListBox1.Perform(LB_SETSEL,0,i);
{$ENDIF}
      Inc(i);
    End;
  End;
  Item:=0;
  Errors:=0;
	If CheckBox3.Checked Then WriteOut(' Rebuilding index...');
  Repeat
{$IFDEF WINDOWS}
	 	If Item>0 Then ListBox1.Perform(LB_SETSEL,0,Item-1);
  	ListBox1.Perform(LB_SETSEL,1,Item);
{$ENDIF}
		AssignFile(Input,ListBox1.Items.Strings[Item]);
		ChDir(ConfigDir);
		AssignFile(Output,'$TEMP.IDX');
  	AssignFile(Log,MaskEdit3.Text);
		If CheckBox1.Checked Then
  	Begin
	  	{$I-}
	  	FileMode:=0;
			Reset(Input,1);
  		FileMode:=2;
			{$I+}
  	End
	  Else
  	Begin
	 		{$I-}
	  	Reset(Input,1);
		  {$I+}
	  End;
  	If IOResult<>0 Then
		Begin
			WriteOut(' Can not open the file.');
			EnableButtons;
	    Exit;
  	End;
	  Seek(Input,4);
    BlockRead(Input,AVISize,4);
  	BlockRead(Input,ChunkName[1],8);
	  ChunkName[0]:=#8;
  	If ChunkName<>'AVI LIST' Then
	  Begin
  		WriteOut(' This is not an AVI file.');
    	CloseFile(Input);
	    EnableButtons;
  	  Exit;
	  End;
		{$I-}
		Rewrite(Output,1);
		{$I+}
		If IOResult<>0 Then
		Begin
			WriteOut(' Cannot create temporary index file.');
	    CloseFile(Input);
  	  EnableButtons;
    	Exit;
	  End;
		If CheckBox3.Checked Then
	  Begin
			{$I-}
			Reset(Log);
			{$I+}
			If IOResult<>0 Then
	    Begin
				{$I-}
				Rewrite(Log);
				{$I+}
				If IOResult<>0 Then
  		  Begin
					WriteOut(' Cannot create log file.');
  	  		CloseFile(Input);
	    	 	CloseFile(Output);
		    	EnableButtons;
	  		  Exit;
			  End
  	    Else
	  	  Begin
					CloseFile(Log);
	   		  Append(Log);
		    End;
    	End
	   	Else
  	  Begin
				CloseFile(Log);
   	  	Append(Log);
	    End;
  	End;
		If CheckBox1.Checked Then
  	Begin
    	If (MaskEdit2.Text='') Or (MaskEdit2.Text='./') Or (MaskEdit2.Text='.\') Then
      AssignFile(Backup,ExtractFilePath(ListBox1.Items.Strings[Item])+'DivFix.'+
      					 ExtractFileName(ListBox1.Items.Strings[Item]))
      Else
      AssignFile(Backup,ExtractFilePath(MaskEdit2.Text)+'DivFix.'+
      					 ExtractFileName(ListBox1.Items.Strings[Item]));
			{$I-}
			Rewrite(Backup,1);
			{$I+}
			If IOResult<>0 Then
			Begin
				WriteOut(' Cannot create backup file.');
	    	CloseFile(Input);
	    	CloseFile(Output);
				If CheckBox3.Checked Then CloseFile(Log);
  		  Erase(Output);
  	  	EnableButtons;
		    Exit;
		  End;
	  End;
		If CheckBox3.Checked Then
	  Begin
  		Logging:=True;
			WriteOut(' Index rebuilding for file: '+ListBox1.Items.Strings[Item]);
	  End
  	Else WriteOut(' Index rebuilding for file: '+ListBox1.Items.Strings[Item]);
	 	Chunkname[0]:=#4;
    Codec[0]:=#4;
		Seek(Input,112);
    BlockRead(Input,Codec[1],4);
    Codec:=UpperCase(Codec);
    Seek(Input,128);
    BlockRead(Input,Scale,4);
    BlockRead(Input,Rate,4);
	 	Position:=16;
  	Size:=0;
  	Repeat
 			Position:=Position+Size;
	  	Seek(Input,Position);
  	  BlockRead(Input,Size,4);
 	  	BlockRead(Input,Chunkname[1],4);
	   	Inc(Position,8);
  	Until Chunkname='movi';
	 	StreamStart:=Position-4;
  	StreamSize:=Size;
		IndexStart:=CheckOtherIndex(Input);
	  If IndexStart=0 Then IndexStart:=FileSize(Input);
	 	Chunkname:='idx1';
  	BlockWrite(Output,Chunkname[1],4);
	 	BlockWrite(Output,Size,4);
 		LastIndexPosition:=FilePos(Output);
	  Position:=4;
 		i:=0;
	  Frame:=0;
  	Difference:=0;
    IndexDifference:=0;
	  Interleaved:=False;
  	StopButton:=False;
	  Seek(Input,0);
  	If CheckBox1.Checked Then
	  Begin
		 	For k:=1 To (StreamStart+4) Div 32768 Do
			Begin
				BlockRead(Input,Buffer,32768,Temp);
				BlockWrite(Backup,Buffer,Temp);
			End;
			BlockRead(Input,Buffer,((StreamStart+4) Mod 32768),Temp);
			BlockWrite(Backup,Buffer,Temp);
	  End;
  	Repeat
    	ProgressBar1.Position:=Position Div ((FileSize(Input)-StreamStart) Div 100);
	    If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
	 		Else Seek(Input,StreamStart+Position);
			BStartRead:
   		If Not Eof(Input) Then
	    Begin
			  BlockRead(Input,Chunkname[1],4,Temp);
    	  If ChunkName='LIST' Then
      	Begin
	      	Seek(Input,FilePos(Input)+8);
  	      Inc(Position,12);
    	    Goto BStartRead;
				End;
	      If ChunkName='JUNK' Then
  	    Begin
    	  	BlockRead(Input,Size,4);
      	  Position:=Position+Size+8;
          Inc(Difference,(Size+8));
          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
      		Else Seek(Input,StreamStart+Position);
					Goto BStartRead;
				End;
    	  Text2:=Copy(ChunkName,3,2);
      	If (Copy(ChunkName,1,2)='ix') Or (Text2='ix') Then
	      Begin
  	      Inc(Position,16);
          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
      		Else Seek(Input,StreamStart+Position);
      	  Interleaved:=True;
        	Goto BStartRead;
				End;
  	    If Not Eof(Input) Then
    	  Begin
      		If ((ChunkName[1] In Number) And (ChunkName[2] In Number)) And
        	   ((Text2='dc') Or (Text2='db') Or (Text2='wb')) Then
	        Begin
  	      	If (Text2='dc') Or (Text2='db') Then
            Begin
            	If Frame=0 Then
              Begin
              	BlockRead(Input,Size,4);
               	BlockRead(Input,KeyType,4);
                If KeyType=65536 Then KeyType:=1
                Else If KeyType=$b0010000 Then KeyType:=2
//                Else If Codec='DIVX' Then KeyType:=1
                	Else KeyType:=3;
                Seek(Input,FilePos(Input)-8);
              End;
            	Inc(Frame);
            End;
    	      If Interleaved Then
      	    Begin
        	  	Seek(Input,FilePos(Input)-16);
          	  Dec(Position,16);
            	Interleaved:=False;
	          End;
					  BlockRead(Input,Size,4,Temp);
    	      If (Size<0) And (Temp=4) Then
      	    Begin
	          	Inc(Position,4);
		          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
    		  		Else Seek(Input,StreamStart+Position);
    	        BlockRead(Input,Chunkname[1],4,Temp);
      	      If ChunkName='LIST' Then
			  	    Begin
      					Seek(Input,FilePos(Input)+8);
            	  Inc(Position,12);
								Goto BStartRead;
							End;
  	          If ChunkName='JUNK' Then
				      Begin
      					BlockRead(Input,Size,4);
			  	      Position:=Position+Size+8;
			          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
      					Else Seek(Input,StreamStart+Position);
			      	  Goto BStartRead;
							End;
		          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
    		  		Else Seek(Input,StreamStart+Position);
    	        Goto BError;
						End;
		    	  If Not Eof(Input) Then
  		    	Begin
		  				If Size>0 Then BlockRead(Input,FrameType,4)
              Else FrameType:=64;
			    	  j:=(((Position+Size) Div 2)+((Position+Size) Mod 2))*2+8;
              If StreamStart+j-1>IndexStart Then Seek(Input,IndexStart)
              Else Seek(Input,StreamStart+j-1);
				   	  If Not Eof(Input) Then
  	  			  Begin
              	If ((Text2='dc') Or (Text2='db')) And (((KeyType=1) And (FrameType=65536))
                Or ((KeyType=2) And (FrameType=$b0010000))
                Or ((KeyType=3) And (FrameType And 64=0))) Then
                	If Size>0 Then LastIndexPosition:=FilePos(Output);
                LastIndex:=FilePos(Output);
							  BlockWrite(Output,Chunkname[1],4);
              	Text2:=Copy(ChunkName,3,2);
							  If ((Text2='dc') Or (Text2='db') Or (Text2='wb')) And
  	            	 ((Chunkname[1]In Number) And (ChunkName[2] In Number)) Then
	                If ((Text2='wb') Or (((KeyType=1) And (FrameType=65536))
                  Or ((KeyType=2) And (FrameType=$b0010000))
                  Or ((KeyType=3) And (FrameType And 64=0)))) And (Size>0) Then
                     BlockWrite(Output,KeyFrame,4)
  								Else BlockWrite(Output,NormFrame,4);
			  				If CheckBox2.Checked Then
	              Begin
  	            	j:=Position-Difference;
    	          	BlockWrite(Output,j,4);
      	        End
        	      Else BlockWrite(Output,Position,4);
						  	BlockWrite(Output,Size,4);
            	  j:=Position;
	 		  				Position:=(((Position+Size) Div 2)+((Position+Size) Mod 2))*2+8;
			          If StreamStart+j>IndexStart Then Seek(Input,IndexStart)
      					Else Seek(Input,StreamStart+j);
  	            If CheckBox1.Checked Then
    	          Begin
                	If ((Text2='dc') Or (Text2='db')) And (((KeyType=1) And (FrameType=65536))
                  Or ((KeyType=2) And (FrameType=$b0010000))
                  Or ((KeyType=3) And (FrameType And 64=0))) Then
                  	If Size>0 Then LastBackupPosition:=FilePos(Backup);
                  LastFrame:=FilePos(Backup);
	      	        If Position-j>32768 Then
  	      	      Begin
    	      	    	For k:=1 To (Position-j) Div 32768 Do
      	      	    Begin
											BlockRead(Input,Buffer,32768,Temp);
	  	    	      	  BlockWrite(Backup,Buffer,Temp);
		          	    End;
  	            	  BlockRead(Input,Buffer,((Position-j) Mod 32768),Temp);
	 		            	BlockWrite(Backup,Buffer,Temp);
  	  	          End
    	  	        Else
      	  	      Begin
	      	  	      BlockRead(Input,Buffer,Position-j,Temp);
  	      	  	    BlockWrite(Backup,Buffer,Temp);
            	  	End;
	              End;
				  		  Inc(i);
    				 	End;
   					End;
        	End
	        Else
  	      Begin
    	    	BError:
      	    If Chunkname<>'idx1' Then
        	  Begin
            	Inc(Errors);
	          	Str(Frame,Text);
              Time:=(Frame*Scale) Div Rate;
              Str(Time Div 3600:2,Hour);
              Str(Time Div 60:2,Minute);
              Str(Time Mod 60:2,Second);
							ZeroAlign(Hour);
							ZeroAlign(Minute);
							ZeroAlign(Second);
		        	Text:=' Corrupted data detected at frame '+Text+' ('+Hour+':'+Minute
            					+':'+Second+')';
  		        If FilePos(Output)>16 Then Seek(Output,FilePos(Output)-16);
							WriteOut(Text);
        	    Str(StreamStart+Position,Text);
          	  Text:=' Error offset: '+Text+' ($'+IntToHex(StreamStart+Position,8)+')';
            	WriteOut(Text);
              IndexDifference:=(FilePos(Output)-LastIndexPosition) Div 16;
              Dec(i,IndexDifference+1);
	            Seek(Output,LastIndexPosition);
  	          If CheckBox1.Checked Then
              	If LastBackupPosition>0 Then
                Begin
                	Seek(Backup,LastBackupPosition);
                End;
    	        j:=Position;
      		    Repeat
			          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
      					Else Seek(Input,StreamStart+Position);
          		  If Not Eof(Input) Then
            		Begin
	      	  			BlockRead(Input,Buffer[1],32768,Temp);
                	k:=1;
		              Repeat
			        	  	If ((Chr(Buffer[k])='d') Or (Chr(Buffer[k])='w')) Then
	  		        	  Begin
 		  			        	If ((Chr(Buffer[k+1])='c') Or (Chr(Buffer[k+1])='b')) Then
     	  		          Begin
							          If StreamStart+Position+k-3>IndexStart Then Seek(Input,IndexStart)
							      		Else Seek(Input,StreamStart+Position+k-3);
 	      	  		        If Not Eof(Input) Then BlockRead(Input,ChunkName[1],4);
 	      	  		        If Not Eof(Input) Then BlockRead(Input,Size,4);
 	      	  		        If Not Eof(Input) Then BlockRead(Input,FrameType,4);
   	      	  		    End;
     	      	  		End;
		  	          	Inc(k);
	                  Text2:=Copy(ChunkName,3,2);
									Until (((Text2='dc') Or (Text2='db')) And ((ChunkName[1] In Number) And
                  			(ChunkName[2] In Number)) And (((KeyType=1) And (FrameType=65536))
                        Or ((KeyType=2) And (FrameType=$b0010000))
                        Or ((KeyType=3) And (FrameType And 64=0))))
                        Or (Chunkname='idx1') Or (k>Temp);
        	        Inc(Position,k-3);
	  	    	    End;
							  Application.ProcessMessages;
						  	If StopButton Then
							  Begin
							  	WriteOut(' Index rebuilding aborted...');
							    ProgressBar1.Position:=0;
						  	  StopButton:=False;
									CloseFile(Input);
									CloseFile(Output);
            	    If CheckBox1.Checked Then CloseFile(Backup);
              	  If CheckBox3.Checked Then CloseFile(Log);
							 		Erase(Output);
	                EnableButtons;
							   	Exit;
							  End;
      	        Text2:=Copy(ChunkName,3,2);
    	  	    Until (((Text2='dc') Or (Text2='db') Or (Text2='wb')) And
          	  		  ((ChunkName[1] In Number) And (ChunkName[2] In Number))
                    And (((KeyType=1) And (FrameType=65536))
                    Or ((KeyType=2) And (FrameType=$b0010000))
                    Or ((KeyType=3) And (FrameType And 64=0))))
                    Or (Chunkname='idx1') Or Eof(Input);
	         		If Not Eof(Input) Then Dec(Position)
              Else
              Begin
              	If CheckBox1.Checked Then
                Begin
	              	Seek(Backup,LastFrame);
  	              Truncate(Backup);
                End;
                Seek(Output,LastIndex);
                Truncate(Output);
                Inc(i,IndexDifference-2);
              End;
							If CheckBox1.Checked Then
    	        Begin
      	      	If Not(CheckBox2.Checked) Then
        	      Begin
              	  If StreamStart+j>IndexStart Then Seek(Input,IndexStart)
				      		Else Seek(Input,StreamStart+j);
  		      	    If Position-j>32768 Then
	  	        	  Begin
      	        		For k:=1 To (Position-j) Div 32768 Do
     	  	        	Begin
											BlockRead(Input,Buffer,32768,Temp);
	  	    	  	      BlockWrite(Backup,Buffer,Temp);
		         	  	  End;
      	       	  	BlockRead(Input,Buffer,((Position-j) Mod 32768),Temp);
		 	  	         	BlockWrite(Backup,Buffer,Temp);
  	      	      End
    		    	    Else
      		    	  Begin
	    	  	    	  BlockRead(Input,Buffer,Position-j,Temp);
  	      		    	BlockWrite(Backup,Buffer,Temp);
	          	  	End;
  	            End
    	          Else
                Difference:=FilePos(Input)-LastBackupPosition-12;
      	      End;
        	  End
          	Else
	          Begin
  	        	Seek(Input,FilePos(Input)+6);
    	        ChunkName[0]:=#2;
      	      BlockRead(Input,ChunkName[1],2);
        	    Seek(Input,FilePos(Input)-8);
          	  If (ChunkName='dc') Or (ChunkName='wb') Or (ChunkName='db') Then
	            Begin
            		ChunkName[0]:=#4;
  	            ChunkName:='idx1';
    	        End
      	      Else
        	    Begin
          	  	ChunkName[0]:=#4;
            	  ChunkName:='0000';
              	Goto BError;
	            End;
  	        End;
    	   	End;
      	End;
	    End;
  	  Application.ProcessMessages;
    	If StopButton Then
	    Begin
  	  	WriteOut(' Index rebuilding aborted...');
    	  ProgressBar1.Position:=0;
      	StopButton:=False;
			  CloseFile(Input);
			 	CloseFile(Output);
    	  If CheckBox1.Checked Then CloseFile(Backup);
      	If CheckBox3.Checked Then CloseFile(Log);
			  Erase(Output);
  	    EnableButtons;
    		Exit;
	    End;
		Until (Eof(Input)) Or (ChunkName='idx1');
	 	Size:=i*16;
  	Seek(Output,4);
	 	BlockWrite(Output,Size,4);
		If CheckBox1.Checked Then
	  Begin
  		If ChunkName='idx1' Then StreamSize:=FilePos(Backup)-StreamStart-4
    	Else StreamSize:=Filesize(Backup)-StreamStart-4;
		  Seek(Backup,StreamStart-4);
      Inc(StreamSize,4);
 			BlockWrite(Backup,StreamSize,4);
	  	Seek(Backup,StreamStart+StreamSize);
	    If (StreamStart+StreamSize) MOD 2=1 Then
  	  Begin
    		Buffer[0]:=0;
	    	BlockWrite(Backup,Buffer,1);
  	  End;
 			Seek(Output,0);
		  Repeat
 				BlockRead(Output,Buffer,32768,Temp);
   			BlockWrite(Backup,Buffer,Temp);
			Until Not(Temp=32768);
      Str(Errors,Text);
      WriteOut(' Finished with '+ListBox1.Items.Strings[Item]+' .');
			WriteOut(' Number of errors: '+Text);
			WriteOut(' Done.');
      WriteOut('');
	    ProgressBar1.Position:=100;
  		Truncate(Backup);
	  	CloseFile(Input);
	 		CloseFile(Output);
  	  CloseFile(Backup);
			If CheckBox3.Checked Then CloseFile(Log);
		  Erase(Output);
  	End
	  Else
  	Begin
  		If ChunkName='idx1' Then StreamSize:=FilePos(Input)-StreamStart-4
	    Else StreamSize:=Filesize(Input)-StreamStart;
      Seek(Input,StreamStart-4);
 			BlockWrite(Input,StreamSize,4);
      If StreamStart+StreamSize>IndexStart Then Seek(Input,IndexStart)
      Else Seek(Input,StreamStart+StreamSize);
  	  If (StreamStart+StreamSize) MOD 2=1 Then
    	Begin
    		Buffer[0]:=0;
	    	BlockWrite(Input,Buffer,1);
  	  End;
 			Seek(Output,0);
		  Repeat
 				BlockRead(Output,Buffer,32768,Temp);
   			BlockWrite(Input,Buffer,Temp);
			Until Not(Temp=32768);
  		Truncate(Input);
      Str(Errors,Text);
      WriteOut(' Finished with '+ListBox1.Items.Strings[Item]+' .');
			WriteOut(' Number of errors: '+Text);
			WriteOut(' Done.');
		  WriteOut('');
			If CheckBox3.Checked Then CloseFile(Log);
  	  ProgressBar1.Position:=100;
	  	CloseFile(Input);
	 		CloseFile(Output);
	  	Erase(Output);
	  End;
    Inc(Item);
  Until Item=ListBox1.Items.Count;
	If CheckBox3.Checked Then
  Begin
  	Logging:=False;
		WriteOut(' Done.');
		WriteOut('');
  End;
	If Autoclearlist1.Checked Then ListBox1.Items.Clear;
{$IFDEF WINDOWS}
	ListBox1.Perform(LB_SETSEL,0,Item-1);
{$ENDIF}
  EnableButtons;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
{$IFDEF WINDOWS}
	If Autoclear1.Checked Then RichEdit1.Clear;
{$ELSE}
	If Autoclear1.Checked Then Memo1.Clear;
{$ENDIF}
	DisableButtons;
  If ListBox1.Items.Count=0 Then
  Begin
		WriteOut(' No file selected.');
    EnableButtons;
  	Exit;
  End;
	Item:=0;
	If CheckBox3.Checked Then WriteOut(' Stripping index...');
  Repeat
		AssignFile(Input,ListBox1.Items.Strings[Item]);
    AssignFile(Log,MaskEdit3.Text);
	  {$I-}
		Reset(Input,1);
		{$I+}
  	If IOResult<>0 Then
		Begin
			WriteOut(' Can not open the file.');
	    EnableButtons;
  	  Exit;
	  End;
		If CheckBox3.Checked Then
	  Begin
			{$I-}
			Reset(Log);
			{$I+}
			If IOResult<>0 Then
  	  Begin
				{$I-}
				Rewrite(Log);
				{$I+}
        i:=ioresult;
				If {IOResult}i<>0 Then
  		  Begin
					WriteOut(' Cannot create log file.');
    			CloseFile(Input);
		    	EnableButtons;
		 		  Exit;
			  End
  	    Else
	 		  Begin
					CloseFile(Log);
	 		  	Append(Log);
		    End;
  	 	End
		 	Else
  	  Begin
				CloseFile(Log);
   	 		Append(Log);
		  End;
    End;
  	Seek(Input,8);
	  BlockRead(Input,ChunkName[1],8);
  	ChunkName[0]:=#8;
	  If ChunkName<>'AVI LIST' Then
  	Begin
			WriteOut(' This is not an AVI file.');
  	  CloseFile(Input);
	    EnableButtons;
  	  Exit;
	  End;
		If CheckBox3.Checked Then
	  Begin
  		Logging:=True;
			WriteOut(' Stripping index for file: '+ListBox1.Items.Strings[Item]);
	  End
  	Else WriteOut(' Stripping index for file: '+ListBox1.Items.Strings[Item]);
	 	Position:=16;
  	Size:=0;
	 	Chunkname[0]:=#4;
  	Repeat
	 		Position:=Position+Size;
  		Seek(Input,Position);
	    BlockRead(Input,Size,4);
 		  BlockRead(Input,Chunkname[1],4);
	   	Inc(Position,8);
  	Until Chunkname='movi';
	 	StreamStart:=Position-4;
  	StreamSize:=Size;
		IndexStart:=CheckOtherIndex(Input);
    If IndexStart=0 Then
    Begin
  		WriteOut(' Unexpected end of file, index not found.');
	    CloseFile(Input);
	    If CheckBox3.Checked Then CloseFile(Log);
  	  EnableButtons;
	    Exit;
		End;
    Seek(Input,IndexStart);
		Truncate(Input);
  	Seek(Input,StreamStart-4);
		BlockWrite(Input,StreamSize,4);
  	CloseFile(Input);
		WriteOut(' Done.');
    WriteOut('');
		If CheckBox3.Checked Then CloseFile(Log);
    Inc(Item);
  Until Item=ListBox1.Items.Count;
	If CheckBox3.Checked Then
  Begin
  	Logging:=False;
		WriteOut(' Done.');
		WriteOut('');
  End;
	If Autoclearlist1.Checked Then ListBox1.Items.Clear;
	EnableButtons;
end;

procedure TForm1.Button3Click(Sender: TObject);
Label CError;
Label CStartRead;

begin
{$IFDEF WINDOWS}
	If Autoclear1.Checked Then RichEdit1.Clear;
{$ELSE}
	If Autoclear1.Checked Then Memo1.Clear;
{$ENDIF}
	DisableButtons;
	If ListBox1.Items.Count=0 Then
  Begin
		WriteOut(' No file selected.');
    EnableButtons;
  	Exit;
  End;
  Item:=0;
  Errors:=0;
	If CheckBox3.Checked Then WriteOut(' Error checking... ');
  Repeat
		AssignFile(Input,ListBox1.Items.Strings[Item]);
  	AssignFile(Log,MaskEdit3.Text);
	  {$I-}
  	FileMode:=0;
		Reset(Input,1);
  	FileMode:=2;
		{$I+}
  	If IOResult<>0 Then
		Begin
  		WriteOut(' Can not open the file.');
    	EnableButtons;
	    Exit;
  	End;
		If CheckBox3.Checked Then
  	Begin
			{$I-}
			Reset(Log);
			{$I+}
			If IOResult<>0 Then
	    Begin
				{$I-}
				Rewrite(Log);
				{$I+}
				If IOResult<>0 Then
  		  Begin
					WriteOut(' Cannot create log file.');
  	  		CloseFile(Input);
	    		EnableButtons;
		  	  Exit;
			  End
    	  Else
	    	Begin
					CloseFile(Log);
	   		  Append(Log);
		    End;
	    End
  	 	Else
    	Begin
				CloseFile(Log);
  	 	  Append(Log);
    	End;
	  End;
  	Seek(Input,8);
	  BlockRead(Input,ChunkName[1],8);
  	ChunkName[0]:=#8;
	  If ChunkName<>'AVI LIST' Then
  	Begin
	  	WriteOut(' This is not an AVI file.');
  	  CloseFile(Input);
			If CheckBox3.Checked Then CloseFile(Log);
	    EnableButtons;
  	  Exit;
	  End;
		If CheckBox3.Checked Then
	  Begin
  		Logging:=True;
			WriteOut(' Error checking for file: '+ListBox1.Items.Strings[Item]);
	  End
  	Else WriteOut(' Error checking for file: '+ListBox1.Items.Strings[Item]);
	  WriteOut(' NOTE: The error checking is not perfect!');
 		Chunkname[0]:=#4;
    Seek(Input,128);
    BlockRead(Input,Scale,4);
    BlockRead(Input,Rate,4);
 		Position:=16;
	  Size:=0;
	  Repeat
 			Position:=Position+Size;
  		Seek(Input,Position);
	    BlockRead(Input,Size,4);
 		  BlockRead(Input,Chunkname[1],4);
   		Inc(Position,8);
	  Until Chunkname='movi';
 		StreamStart:=Position-4;
	  StreamSize:=Size;
		IndexStart:=CheckOtherIndex(Input);
    If IndexStart=0 Then IndexStart:=FileSize(Input);
 		Chunkname:='idx1';
	  Position:=4;
 		i:=0;
	  Frame:=0;
  	Interleaved:=False;
	  StopButton:=False;
  	Repeat
	    ProgressBar1.Position:=Position Div (FileSize(Input) Div 100);
      If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
   		Else Seek(Input,StreamStart+Position);
	   	If Not Eof(Input) Then
  	  Begin
	    	CStartRead:
			  BlockRead(Input,Chunkname[1],4,Temp);
  	    If ChunkName='LIST' Then
	      Begin
  	    	Seek(Input,FilePos(Input)+8);
	        Inc(Position,12);
  	      Goto CStartRead;
				End;
	      If ChunkName='JUNK' Then
  	    Begin
	      	BlockRead(Input,Size,4);
	        Position:=Position+Size+8;
          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
      		Else Seek(Input,StreamStart+Position);
    	    Goto CStartRead;
				End;
	      Text2:=Copy(ChunkName,3,2);
  	    If (Copy(ChunkName,1,2)='ix') Or (Text2='ix') Then
    	  Begin
      		Seek(Input,FilePos(Input)+12);
	        Inc(Position,16);
          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
      		Else Seek(Input,StreamStart+Position);
    	    Interleaved:=True;
      	  Goto CStartRead;
				End;
  	    If Not Eof(Input) Then
    	  Begin
	      	If ((ChunkName[1] In Number) And (ChunkName[2] In Number)) And
  	         ((Text2='dc') Or (Text2='db') Or (Text2='wb')) Then
    	    Begin
      	  	If (Text2='dc') Or (Text2='db') Then Inc(Frame);
        	  If Interleaved Then
          	Begin
	          	Seek(Input,FilePos(Input)-16);
  	          Dec(Position,16);
    	        Interleaved:=False;
      	    End;
					  BlockRead(Input,Size,4,Temp);
          	If (Size<0) And (Temp=4) Then
	          Begin
  	        	Inc(Position,4);
		          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
    		  		Else Seek(Input,StreamStart+Position);
      	      BlockRead(Input,Chunkname[1],4);
      				If ChunkName='LIST' Then
			    	  Begin
			      		Seek(Input,FilePos(Input)+8);
              	Inc(Position,12);
	      			  Goto CStartRead;
							End;
    	        If ChunkName='JUNK' Then
				      Begin
      					BlockRead(Input,Size,4);
			    	    Position:=Position+Size+8;
			          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
      					Else Seek(Input,StreamStart+Position);
      			  	Goto CStartRead;
							End;
		          If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
    		  		Else Seek(Input,StreamStart+Position);
    	        Goto CError;
      	    End;
		    	  If Not Eof(Input) Then
  		    	Begin
			    	  j:=(((Position+Size) Div 2)+((Position+Size) Mod 2))*2+8;
              If StreamStart+j-1>IndexStart Then Seek(Input,IndexStart)
		      		Else Seek(Input,StreamStart+j-1);
				   	  If Not Eof(Input) Then
  	  			  Begin
	 		  				Position:=(((Position+Size) Div 2)+((Position+Size) Mod 2))*2+8;
			  			  Inc(i);
    			 		End;
	   				End;
  	      End
    	    Else
						CError:
        	  If Chunkname<>'idx1' Then
          	Begin
            	Inc(Errors);
	          	Str(Frame,Text);
              Time:=(Frame*Scale) Div Rate;
              Str(Time Div 3600:2,Hour);
              Str(Time Div 60:2,Minute);
              Str(Time Mod 60:2,Second);
							ZeroAlign(Hour);
							ZeroAlign(Minute);
							ZeroAlign(Second);
		        	Text:=' Corrupted data detected at frame '+Text+' ('+Hour+':'+Minute
            					+':'+Second+')';
							WriteOut(Text);
      	      Str(StreamStart+Position,Text);
        	    Text:=' Error offset: '+Text+' ($'+IntToHex(StreamStart+Position,8)+')';
          	  WriteOut(Text);
      	    	Repeat
              	If StreamStart+Position>IndexStart Then Seek(Input,IndexStart)
			      		Else Seek(Input,StreamStart+Position);
	          	  If Not Eof(Input) Then
  	          	Begin
	  	    	  		BlockRead(Input,Buffer[1],32768,Temp);
      	          j:=1;
	      	        Repeat
		      	  	  	If ((Chr(Buffer[j])='d') Or (Chr(Buffer[j])='w')) And (Not Eof(Input)) Then
	  	      	  	  Begin
		  		    	    	If ((Chr(Buffer[j+1])='c') Or (Chr(Buffer[j+1])='b')) And (Not Eof(Input)) Then
     	  	      	    Begin
                    		If StreamStart+Position+j-3>IndexStart Then Seek(Input,IndexStart)
							      		Else Seek(Input,StreamStart+Position+j-3);
 	      	  	      	  If Not Eof(Input) Then BlockRead(Input,ChunkName[1],4);
	   	      	  	    End;
  	   	      	  	End;
			  	          Inc(j);
      	            Text2:=Copy(ChunkName,3,2);
									Until (((Text2='dc') Or (Text2='db') Or
		      	            (Text2='wb')) And ((ChunkName[1] In Number) And
    		    	          (ChunkName[2] In Number))) Or (Chunkname='idx1') Or (j>Temp);
	  	        	End;
	              Inc(Position,j-3);
  	            Application.ProcessMessages;
						    If StopButton Then
						    Begin
						    	WriteOut(' Error checking aborted...');
						      ProgressBar1.Position:=0;
					  	    StopButton:=False;
              	  CloseFile(Input);
									If CheckBox3.Checked Then CloseFile(Log);
	                EnableButtons;
						    	Exit;
						    End;
      	        Text2:=Copy(ChunkName,3,2);
    	  	    Until (((Text2='dc') Or (Text2='db') Or
          	        (Text2='wb')) And ((ChunkName[1] In Number) And
            	      (ChunkName[2] In Number))) Or (Chunkname='idx1') Or Eof(Input);
	          	If Not Eof(Input) Then Dec(Position);
  	      	End
    	      Else
      	    Begin
        	  	Seek(Input,FilePos(Input)+6);
          	  ChunkName[0]:=#2;
            	BlockRead(Input,ChunkName[1],2);
	            Seek(Input,FilePos(Input)-8);
  	          If (ChunkName='dc') Or (ChunkName='wb') Or (ChunkName='db') Then
    	        Begin
      	      	ChunkName[0]:=#4;
        	      ChunkName:='idx1';
          	  End
            	Else
	            Begin
  	          	ChunkName[0]:=#4;
    	          ChunkName:='0000';
      	        Goto CError;
        	    End
          	End;
	      End;
  	  End;
    	Application.ProcessMessages;
	    If StopButton Then
  	  Begin
    		WriteOut(' Error checking aborted...');
      	ProgressBar1.Position:=0;
	      StopButton:=False;
  	    CloseFile(Input);
				If CheckBox3.Checked Then CloseFile(Log);
	      EnableButtons;
  	  	Exit;
    	End;
		Until (Eof(Input)) Or (ChunkName='idx1');
		Str(Errors,Text);
		WriteOut(' Finished with '+ListBox1.Items.Strings[Item]+' .');
		WriteOut(' Number of errors: '+Text);
		WriteOut(' Done.');
	  WriteOut('');
		If CheckBox3.Checked Then CloseFile(Log);
  	ProgressBar1.Position:=100;
	  CloseFile(Input);
	  Inc(Item);
  Until Item=ListBox1.Items.Count;
	If CheckBox3.Checked Then
  Begin
  	Logging:=False;
    Str(Errors,Text);
    WriteOut(' Finished with '+ListBox1.Items.Strings[Item]+' .');
		WriteOut(' Number of errors: '+Text);
		WriteOut(' Done.');
		WriteOut('');
  End;
	If Autoclearlist1.Checked Then ListBox1.Items.Clear;
	EnableButtons;
end;

procedure TForm1.Exit1Click(Sender: TObject);
begin
	Close;
end;

procedure TForm1.About1Click(Sender: TObject);
begin
	Form1.Enabled:=False;
	Form2.Show;
end;

procedure TForm1.StayTop(Sender: TObject);
begin

	If Stayontop1.Checked Then
  Begin
  	Stayontop1.Checked:=Not(Stayontop1.Checked);
{$IFDEF WINDOWS}
    SetWindowPos(TForm1(Self).Handle,HWND_NOTOPMOST,0,0,0,0,SWP_NOSIZE+SWP_NOMOVE);
{$ENDIF}
  End
  Else
  Begin
  	Stayontop1.Checked:=Not(Stayontop1.Checked);
{$IFDEF WINDOWS}
    SetWindowPos(TForm1(Self).Handle,HWND_TOPMOST,0,0,0,0,SWP_NOSIZE+SWP_NOMOVE);
{$ENDIF}
  End;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
{$IFDEF WINDOWS}
	DropFileTarget1.register(Form1);
{$ENDIF}
  If Tag=0 Then
  Begin
	  GetDir(0,ConfigDir);
{$IFDEF WINDOWS}
 		If Copy(ConfigDir,Length(ConfigDir),1)='\' Then AssignFile(Config,ConfigDir+'DivFix.ini')
    Else AssignFile(Config,ConfigDir+'\DivFix.ini');
{$ELSE}
 		If Copy(ConfigDir,Length(ConfigDir),1)='/' Then AssignFile(Config,ConfigDir+'DivFix.ini')
    Else AssignFile(Config,ConfigDir+'/DivFix.ini');
{$ENDIF}
	  {$I-}
  	Reset(Config);
	  {$I+}
		If IOResult=0 Then
	  Begin
  		While Not(Eof(Config)) Do
    	Begin
				Readln(Config,Text);
				If Copy(Text,1,7)='LastDir' Then
  	    Begin
    	  	Form1.OpenDialog1.InitialDir:=Copy(Text,9,Length(Text)-9);
{$IFDEF WINDOWS}
      	  CfgDir:=Form1.OpenDialog1.InitialDir+'\';
{$ELSE}
      	  CfgDir:=Form1.OpenDialog1.InitialDir+'/';
{$ENDIF}
	      End;
				If Copy(Text,1,7)='DestDir' Then
  	    Begin
    	  	Form1.MaskEdit2.Text:=Copy(Text,9,Length(Text)-7);
      	  CfgDest:=Form1.MaskEdit2.Text;
	      End;
 				If Copy(Text,1,9)='StayOnTop' Then
	  	   	If Copy(Text,11,Length(Text)-9)='1' Then
  	  	  Begin
						StayTop(Self);
	          CfgStay:=True;
		     	End
    	    Else CfgStay:=False;
 				If Copy(Text,1,9)='AutoClear' Then
	  	   	If Copy(Text,11,Length(Text)-9)='1' Then
  	  	  Begin
						Autoclear1.Checked:=True;
	          CfgClear:=True;
		     	End
    	    Else CfgClear:=False;
 				If Copy(Text,1,9)='ClearList' Then
	  	   	If Copy(Text,11,Length(Text)-9)='1' Then
  	  	  Begin
						Autoclearlist1.Checked:=True;
	          CfgCList:=True;
		     	End
    	    Else CfgCList:=False;
      	If Copy(Text,1,12)='KeepOriginal' Then
	  	   	If Copy(Text,14,Length(Text)-12)='1' Then
  	      Begin
    	    	Form1.CheckBox1.Checked:=True;
      	    CfgKeep:=True;
        	End
	        Else CfgKeep:=False;
  	    If Copy(Text,1,6)='CutOut' Then
    	  	If Copy(Text,8,Length(Text)-6)='1' Then
	    	    If Form1.CheckBox2.Enabled Then
        	  Begin
          		Form1.CheckBox2.Checked:=True;
            	CfgCut:=True;
	          End
  	        Else CfgCut:=False;
    	  If Copy(Text,1,9)='LogErrors' Then
      		If Copy(Text,11,Length(Text)-9)='1' Then
        	Begin
        		Form1.CheckBox3.Checked:=True;
	          CfgLog:=True;
  	      End
    	    Else CfgLog:=False;
			End;
  	  CloseFile(Config);
	  End;
  End;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
{$IFDEF WINDOWS}
	DropFiletarget1.Unregister;
{$ENDIF}
  If Tag=0 Then
{$IFDEF WINDOWS}
	  If (CfgDir<>OpenDialog1.InitialDir+'\') Or (CfgDest<>Form1.MaskEdit2.Text) Or
    	 (CfgStay<>Stayontop1.Checked) Or (CfgKeep<>CheckBox1.Checked) Or
       (CfgCut<>CheckBox2.Checked) Or (CfgLog<>CheckBox3.Checked) Or
       (CfgClear<>Autoclear1.Checked) Or (CfgCList<>Autoclearlist1.Checked) Then
{$ELSE}
	  If (CfgDir<>OpenDialog1.InitialDir+'/') Or (CfgDest<>Form1.MaskEdit2.Text) Or
    	 (CfgStay<>Stayontop1.Checked) Or (CfgKeep<>CheckBox1.Checked) Or
       (CfgCut<>CheckBox2.Checked) Or (CfgLog<>CheckBox3.Checked) Or
       (CfgClear<>Autoclear1.Checked) Or (CfgCList<>Autoclearlist1.Checked) Then
{$ENDIF}
	  Begin
		  Rewrite(Config);
{$IFDEF WINDOWS}
    	If OpenDialog1.InitialDir<>'' Then Writeln(Config,'LastDir='+OpenDialog1.InitialDir+'\')
      Else Writeln(Config,'LastDir=.\');
     	If Form1.MaskEdit2.Text<>'' Then Writeln(Config,'DestDir='+Form1.MaskEdit2.Text)
      Else Writeln(Config,'DestDir=.\');
{$ELSE}
    	If OpenDialog1.InitialDir<>'' Then Writeln(Config,'LastDir='+OpenDialog1.InitialDir+'/')
      Else Writeln(Config,'LastDir=./');
     	If Form1.MaskEdit2.Text<>'' Then Writeln(Config,'DestDir='+Form1.MaskEdit2.Text)
      Else Writeln(Config,'DestDir=./');
{$ENDIF}
	    If Stayontop1.Checked Then Writeln(Config,'StayOnTop=1')
  	  Else Writeln(Config,'StayOnTop=0');
      If Autoclear1.Checked Then Writeln(Config,'AutoClear=1')
  	  Else Writeln(Config,'AutoClear=0');
      If Autoclearlist1.Checked Then Writeln(Config,'ClearList=1')
	 	  Else Writeln(Config,'ClearList=0');
     	If CheckBox1.Checked Then Writeln(Config,'KeepOriginal=1')
	    Else Writeln(Config,'KeepOriginal=0');
  	  If CheckBox2.Checked Then Writeln(Config,'CutOut=1')
    	Else Writeln(Config,'CutOut=0');
	    If CheckBox3.Checked Then Writeln(Config,'LogErrors=1')
  	  Else Writeln(Config,'LogErrors=0');
    	CloseFile(Config);
		End;
end;

{$IFDEF WINDOWS}
procedure TForm1.DropFileTarget1Drop(Sender: TObject;
  ShiftState: TShiftState; Point: TPoint; var Effect: Integer);
begin
	ListBox1.Items.AddStrings(DropFileTarget1.Files);
  OpenDialog1.InitialDir:=Copy(ExtractFilePath(ListBox1.Items.Strings[0]),1,
  	Length(ExtractFilePath(ListBox1.Items.Strings[0]))-1);
end;
{$ENDIF}

procedure TForm1.Button4Click(Sender: TObject);
begin
	StopButton:=True;
end;

procedure TForm1.CheckBox1Click(Sender: TObject);
begin
  CheckBox2.Enabled:=Not(CheckBox2.Enabled);
  SpeedButton2.Enabled:=Not(SpeedButton2.Enabled);
  Maskedit2.Enabled:=Not(MaskEdit2.Enabled);
  If Not(CheckBox2.Enabled) Then CheckBox2.Checked:=False;
end;

procedure TForm1.CheckBox3Click(Sender: TObject);
begin
  SpeedButton3.Enabled:=Not(SpeedButton3.Enabled);
  Maskedit3.Enabled:=Not(MaskEdit3.Enabled);
  If Not(CheckBox2.Enabled) Then CheckBox2.Checked:=False;
end;

procedure TForm1.ShowWebPage(Sender: TObject);
begin
{$IFDEF WINDOWS}
	ShellExecute(0,'open',pchar('http://divfix.maxeline.com'),nil,nil,SW_MAXIMIZE);
{$ENDIF}
end;

procedure TForm1.Button5Click(Sender: TObject);
begin
	If OpenDialog1.Execute Then
  Begin
  	OpenDialog1.InitialDir:=Copy(ExtractFilePath(OpenDialog1.FileName),1,
  	Length(ExtractFilePath(OpenDialog1.FileName))-1);
    ListBox1.Items.AddStrings(OpenDialog1.Files);
  End;
end;

procedure TForm1.Button6Click(Sender: TObject);
Var i	:	Cardinal;

begin
	i:=0;
  While i<=ListBox1.Items.Count-1 Do
  	If ListBox1.Selected[i] Then ListBox1.Items.Delete(i)
    Else Inc(i);
end;

procedure TForm1.Button7Click(Sender: TObject);
begin
	ListBox1.Items.Clear;
end;

procedure TForm1.Clear1Click(Sender: TObject);
begin
{$IFDEF WINDOWS}
	RichEdit1.Clear;
{$ELSE}
	Memo1.Clear;
{$ENDIF}
end;

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
{$IFDEF WINDOWS}
	If Key=VK_INSERT Then Button5Click(nil);
  If Key=VK_DELETE Then Button6Click(nil);
{$ENDIF}
end;

procedure TForm1.Autoclear1Click(Sender: TObject);
begin
	Autoclear1.Checked:=Not(Autoclear1.Checked);
end;

procedure TForm1.Autoclearlist1Click(Sender: TObject);
begin
	Autoclearlist1.Checked:=Not(Autoclearlist1.Checked);
end;

end.
