program KD;

uses
  SysUtils;

const
  BSz = 512;

var
 dir:string;
 FoundFiles:array of record
  FN:string;
  FSz:Int64;
  DupFlag:integer
 end;

 Buff1,Buff2:array[0..BSz-1] of byte;

 function FilesEqu(i,j:integer):boolean;
 var
  f1,f2:file;
  Rdn:Int64;
 begin
 if FoundFiles[i].FSz <> FoundFiles[j].FSz then
  Exit(False);
 if FoundFiles[i].FSz = 0 then
  Exit(True);
 AssignFile(f1,FoundFiles[i].FN);
 Reset(f1,1);
 AssignFile(f2,FoundFiles[j].FN);
 Reset(f2,1);
 try
  while not eof(f1) do
   begin
    BlockRead(f1,Buff1,BSz,Rdn);
    BlockRead(f2,Buff2,BSz,Rdn);
    if not CompareMem(@Buff1,@Buff2,Rdn) then
     Exit(False);
   end;
  Result := True;
 finally
  CloseFile(f1);
  CloseFile(f2);
 end;
 end;

var
 FF:TSearchRec;
 i,j:integer;
begin
Writeln('Kill duplicated files in given directory by S.V.Bulba');
Writeln('Version 1.1');
if ParamCount <> 1 then
 begin
  Writeln('  Usage:');
  Writeln('KD <directory_name>');
  Exit;
 end;

dir := ParamStr(1);
SetCurrentDir(dir);
if dir[Length(dir)] <> '\' then
 dir := dir + '\';
dir := dir + '*';

FileMode := 0;

if FindFirst(dir,faAnyFile,FF) = 0 then
 begin
  i := 0;
  repeat
   if FF.Attr and faDirectory = 0 then
    begin
     if i mod 512 = 0 then
      SetLength(FoundFiles,i + 512);
     FoundFiles[i].FN := FF.Name;
     FoundFiles[i].FSz := FF.Size;
     FoundFiles[i].DupFlag := -1;
     Inc(i);
    end;
  until FindNext(FF) <> 0;
  SetLength(FoundFiles,i);
  for i := 0 to Length(FoundFiles) - 1 do
   if FoundFiles[i].DupFlag = -1 then
    for j := i + 1 to Length(FoundFiles) - 1 do
     if FoundFiles[j].DupFlag = -1 then
      if FilesEqu(i,j) then
       begin
        FoundFiles[i].DupFlag := i;
        FoundFiles[j].DupFlag := i;
       end;
  for i := 0 to Length(FoundFiles) - 1 do
   if (FoundFiles[i].DupFlag <> -1) and
      (FoundFiles[i].DupFlag <> i) then
    DeleteFile(FoundFiles[i].FN);
  Writeln('Done.')
 end
else
 Writeln('No one file was found in specified directory');
FindClose(FF);
end.

