-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuMAIN.~pas
1577 lines (1394 loc) · 50.4 KB
/
uMAIN.~pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{*******************************************************************************}
{* *}
{* ANALYSIS OF COMPARISON LEMPEL ZIV WELCH, ARITHMETIC CODING, AND RUN-LENGTH *}
{* ENCODING COMPRESSION ALGORITHMS ON TEXT FILE *}
{* *}
{* Author : Plipus Telaumbanua *}
{* 061401006 *}
{* philipstel@gmail.com *}
{* http://www.pilipstel.web.id *}
{* *}
{* Computer Science *}
{* University of North Sumatera *}
{* 2010-2011 *}
{* *}
{*******************************************************************************}
unit uMAIN;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ComCtrls, ToolWin, ImgList, Grids, ValEdit,
ExtCtrls, StdCtrls, DBGrids, functions, XPMan, uOPTION, Buttons, uAbout;
type
TArrayInt = array of Integer;
TArrayChar = array[chr(0)..chr(255)] of integer;
TfrmMAIN = class(TForm)
StatusBar1: TStatusBar;
ImageList1: TImageList;
MainMenu1: TMainMenu;
File1: TMenuItem;
Customize1: TMenuItem;
CoolBar2: TCoolBar;
Open1: TMenuItem;
SaveAs1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
Compression1: TMenuItem;
Decompression1: TMenuItem;
N2: TMenuItem;
Settings1: TMenuItem;
Option1: TMenuItem;
N8Bits1: TMenuItem;
N9Bits1: TMenuItem;
N10Bits1: TMenuItem;
N11Bits1: TMenuItem;
N12Bits1: TMenuItem;
Help1: TMenuItem;
HelpTopic1: TMenuItem;
About1: TMenuItem;
CoolBar3: TCoolBar;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
LblFileName: TLabel;
LblFileType: TLabel;
LblFileSize: TLabel;
LblFileSource: TLabel;
CompressLZW: TButton;
CompressAC: TButton;
CompressRLEBWT: TButton;
DecompressLZW: TButton;
DecompressAC: TButton;
DecompressRLEBWT: TButton;
SaveDialog1: TSaveDialog;
OpenDialog1: TOpenDialog;
XPManifest1: TXPManifest;
StringGrid1: TStringGrid;
OpenDialog2: TOpenDialog;
CoolBar1: TCoolBar;
Panel1: TPanel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButton5: TSpeedButton;
SpeedButton6: TSpeedButton;
SpeedButton7: TSpeedButton;
SaveDialog2: TSaveDialog;
SpeedButton8: TSpeedButton;
Loading: TStaticText;
procedure FormCreate(Sender: TObject);
procedure CompressLZWClick(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure N8Bits1Click(Sender: TObject);
procedure N9Bits1Click(Sender: TObject);
procedure N10Bits1Click(Sender: TObject);
procedure N11Bits1Click(Sender: TObject);
procedure N12Bits1Click(Sender: TObject);
procedure Option1Click(Sender: TObject);
procedure DecompressLZWClick(Sender: TObject);
procedure SpeedButton5Click(Sender: TObject);
procedure SettingDictionary(BitLength: Integer);
procedure GridTitle(WhatType: string);
procedure CompressActive();
procedure DecompressActive();
procedure OpenFile();
procedure SaveAs();
procedure SaveAutomatically(Res, Properties: String; Compress: Boolean);
procedure Compression1Click(Sender: TObject);
procedure Decompression1Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure SpeedButton4Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure Open1Click(Sender: TObject);
procedure SaveAs1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton7Click(Sender: TObject);
procedure SpeedButton8Click(Sender: TObject);
procedure CompressRLEBWTClick(Sender: TObject);
procedure DecompressRLEBWTClick(Sender: TObject);
procedure CompressACClick(Sender: TObject);
procedure DecompressACClick(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure HelpTopic1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
DEFAULT_ASCII_SIZE = 255; { for initial dictionary }
DEFAULT_BUFFER_SIZE = 2000000; { buffer size 2 mb ( 2 million bytes) }
END_OF_HEADER = '$'; { stop if this found while reading the header }
END_OF_FILE = Chr($FF);
RLE_MARKER_BYTE = '#';
var
frmMAIN: TfrmMAIN;
{ File Handling Declaration }
IntFileSize, NumRead: Integer; { file size (num bytes) and indicator }
StrFileName: String; { file name}
FileHandling: File; { for untyped file instead of textFile }
Buffer: Array[0..DEFAULT_BUFFER_SIZE] of Char;
{ LZW Properties }
SetDictionaryLength, SetBitsLength: Integer; { for dictionary arbitary length }
Dictionary: Array Of String;
{ AC Properties }
SymbolLow, SymbolHigh, Frequency: TArrayChar;
Factor, TotalScaled: Integer;
ACFileType: String;
HeadMod, HeadFSize : Integer;
{ BWT Properties }
Buffer2: String; { Buffer2 holds the copy of Buffer for F building }
{ Others }
{ Simply go to option menu to understand this }
CompressSavingPath, DecompressSavingPath: String;
EncodedStream, DecodedStream: String; { used for LZW, AC, and RLE+BWT }
CompressGridCounter, DecompressGridCounter, HeaderIndexPosition: Integer;
OpenDialogType: Boolean; { true for compression's openDialog and false for
decompression's OpenDialog }
implementation
{$R *.dfm}
{**
* This function is used to search the string characters in the dictionary using
* by sequential search.
* @Param 1 : <string> Str : symbol being searched
* @Param 2 : <array> Dict : dictionary
* @Return : <boolean> return TRUE if it's found, otherwise FALSE.
* @Effect : None
**}
function IsInDictionary(Str: string): Boolean;
var
I : Integer;
Found : Boolean;
begin
Found := False;
if Length(Str) = 1 then begin
Found := True;
end else begin
for I := 256 to Length(Dictionary) - 1 do begin
if Str = Dictionary[I] then begin
Found := True;
Break; { stop searching if it's found }
end;
Found := False;
end;
end;
Result := Found;
end;
{**
* This function is used to take the 'index' for current symbol from the dictionary
* @Param 1 : <string> Str : symbol searched
* @Return : <integer> return the index for its symbol
* @Effect : None
**}
function GetIndex(Str: string): Integer;
var
I, Index : Integer;
begin
Index := 0;
for I := 0 to Length(Dictionary) - 1 do begin
if Str = Dictionary[I] then begin
Index := I;
Break;
end;
end;
Result := Index;
end;
{**
* This function is used to change the 'CodeWord' in binary to be 'ASCII' characters
* that fix in 8 bits for each character. (Used for Compresssion)
* @Param 1 : <string> CW : CodeWord in binary. Ex: 011011100...
* @Return : <string> return the 'CodeWord' to ASCII characters as a final encoding.
* @Effect : Make the length of 'CodeWord' MOD 8 is 0
**}
function CodewordToAscii(CW: String): String;
var
AfterRestRemoved, ActualRest, ActualCodeword, AsciiOutput: String;
Rest: Integer;
I: LongInt;
begin
ActualCodeword := CW;
{ It turns out that the length of CW mod 8 is not 0. Wow that's bad! we need to pad it }
if Length(CW) mod 8 <> 0 then begin
Rest := Length(CW) mod 8;
AfterRestRemoved := SubStr(CW, 1, Length(CW) - Rest);
ActualRest := BitPadding(SubStr(CW, (Length(CW) - Rest) + 1, Rest), 8, 'RIGHT');
ActualCodeword := AfterRestRemoved + ActualRest; { finally it mod 8 is 0}
end;
{ It turns out that the length of CW mod 8 is 0. So feel free to change it to ASCII character }
I := 1;
while I <= Length(ActualCodeWord) do begin
AsciiOutput := AsciiOutput + Chr(BinerToDecimal(SubStr(ActualCodeWord, I, 8)));
Inc(I, 8);
end;
Result := AsciiOutput;
end;
{**
* This function is used for decoding. This function works by changing the ASCII characters
* (encoded stream) to a sequence of biner. (Used for Decompression)
* that fix in 8 bits for each character.
* @Param 1 : <array> Buffer : Buffer (encoded stream) which containts human unreadable characters
* @Parm 2 : <LongInt) IntFileSize : The file size
* @Return : <string> Collection of biners which fix with 'Bits' length.
* @Effect : Make ASCII characters to biners and fix with 'Bits' length.
**}
function AsciiToCodeword(var Buffer: Array of Char; intFSize: LongInt): String;
var
InBiner, EightBits, RemovePadding: String;
Rest, Bits: Integer;
I: LongInt;
begin
{ get the header information }
Bits := SetBitsLength;
{ read buffer from this position, add one since buffer from 0, while HeaderIndexPosition from 1 }
I := HeaderIndexPosition + 1;
{ read the ASCII character (encoded stream). Read one byte at a time }
while I < IntFSize - 1 do begin
InBiner := DecimalToBiner(Ord(Buffer[I])); { change to biner per character }
EightBits := EightBits + BitPadding(InBiner, 8, 'LEFT'); { make every character fix in 8 bits }
Inc(I);
end;
{ we need to check it again if it's fix in 'Bits' size }
if Length(EightBits) mod Bits <> 0 then begin
Rest := Length(EightBits) mod Bits;
RemovePadding := SubStr(EightBits, 1, Length(EightBits) - Rest);
Result := RemovePadding;
end else begin
Result := EightBits;
end;
end;
{**
* This procedure is used to set the arbitary dictionary length
* @Param 1 : <integer> BitLength : the bit length being used
* @Return : None
* @Effect : Change the bit and dictionary being used
**}
procedure TfrmMAIN.SettingDictionary(BitLength: Integer);
begin
case (BitLength) of
8: begin
N8Bits1.Checked := True;
N9Bits1.Checked := False;
N10Bits1.Checked := False;
N11Bits1.Checked := False;
N12Bits1.Checked := False;
end;
9: begin
N8Bits1.Checked := False;
N9Bits1.Checked := True;
N10Bits1.Checked := False;
N11Bits1.Checked := False;
N12Bits1.Checked := False;
end;
10: begin
N8Bits1.Checked := False;
N9Bits1.Checked := False;
N10Bits1.Checked := True;
N11Bits1.Checked := False;
N12Bits1.Checked := False;
end;
11: begin
N8Bits1.Checked := False;
N9Bits1.Checked := False;
N10Bits1.Checked := False;
N11Bits1.Checked := True;
N12Bits1.Checked := False;
end;
12: begin
N8Bits1.Checked := False;
N9Bits1.Checked := False;
N10Bits1.Checked := False;
N11Bits1.Checked := False;
N12Bits1.Checked := True;
end;
end;
end;
{** This function is used to get the opposite bits due to the underflow
* @param1 : <string> Bit : bit input '0' or '1'
* @return : <string> '0' to '1', '1' to '0'
**}
function OppositeBit(Bit: String): String;
begin
if Bit = '0' then begin
Result := '1';
end else begin
Result := '0';
end;
end;
{** This function is used to shift out the msb as well as shift in lsb
* @param1 : <string> Biner : 110011
* @param2 : <string> ShiftIn : '0' or '1'
* @return : ShiftMSB('abcde', '0') would return 'bcde0'
**}
function ShiftMSB(Biner: String; ShiftIn: String): String;
begin
Result := Copy(Biner, 2, Length(Biner) - 1) + ShiftIn;
end;
{** this function is used to revomve the 2nd bit and then shift in
* the 'shiftIn' bit in the most left of 'Biner'
**}
function ShiftUnderflow(Biner: String; ShiftIn: String): String;
var
FirstBit, ThirdBit: String;
begin
FirstBit := Copy(Biner, 1, 1);
ThirdBit := Copy(Biner, 3, Length(Biner) - 1);
Result := FirstBit + ThirdBit + ShiftIn;
end;
{** This function is used to build the model for counting the lower and
* upper bound of symbol.
**}
procedure BuildProbabilities(var Lower, Upper: TArrayChar);
var
Temp: Char;
I: Integer;
begin
Upper[Temp] := 0;
for I := 0 to 255 do begin
Lower[Chr(I)] := Upper[Temp];
Upper[Chr(I)] := Frequency[Chr(I)] + Upper[Temp];
Temp := Chr(I);
end;
end;
{** This padding will divide all bits in 'padding'
* this is obvious different with bitpadding() function
**}
function OutputBits(Biner: String; Padding: Integer): String;
var
N, Modulus, Ins: Integer;
begin
N := Length(Biner);
Modulus := N mod Padding;
if Modulus <> 0 then begin
Ins := N + (Padding - Modulus);
Biner := BitPadding(Biner, Ins, 'RIGHT');
end;
Result := Biner;
end;
{ read AC header }
procedure ReadACHeader();
var
I: Integer;
Dexp : TStringList;
begin
Dexp := Explode('|', Buffer);
ACFileType := Dexp[0];
if ACFileType = 'ac' then begin
TotalScaled := 0;
for I := 1 to 256 do begin
Frequency[Chr(I - 1)] := StrToInt(Dexp[I]);
TotalScaled := TotalScaled + StrToInt(Dexp[I]);
end;
HeadMod := StrToInt(Dexp[257]);
HeadFSize := StrToInt(Dexp[258]);
// now we have low and high range for each symbol
BuildProbabilities(SymbolLow, SymbolHigh);
// Get the buffer's index of end of header character position, so that we can start from there.
HeaderIndexPosition := 0;
for I := 0 to IntFileSize - 1 do begin
if Buffer[I] = END_OF_HEADER then begin
HeaderIndexPosition := I;
Break;
end;
end;
end;
end;
function WriteString(Chr: Char; Long: Integer): String;
var
I: Integer;
Output: String;
begin
Output := '';
for I := 1 to Long do begin
Output := Output + Chr;
end;
Result := Output;
end;
{** This function is used to rotate a string starting from I index
* to look the effect cuased by it, simply run this Rotate('PHILIPS_TEL', 3) it will
* give you 'LIPS_TELPHI'
**}
function Rotate(Str: String; I: Integer): String;
var
RotatedStrings: String;
N: Integer;
begin
N := IntFileSize;
RotatedStrings := Copy(Str, I + 1, N - (I * 1)) + Copy(Str, 1, (I * 1) );
Result := RotatedStrings;
end;
{** This function is used to compare a byte with the next byte, comparing will be continue
* until the difference is found. (Theorically and practically this will be always occurs, since
* there is an unique EOF (indicator)...hehe..nice!
* @param : <integer> x, y: indicies to be compared
* @return :<boolean> (try guess, what is it??? lol....)
**}
function Compare(X, Y: Integer): Boolean;
begin
while Buffer[X] = Buffer[Y] do begin
Inc(X);
Inc(Y);
end;
if Buffer[X] < Buffer[Y] then begin
Result:= True;
end else begin
Result:= False;
end;
end;
{** This is used to ConcatArray two sorted arrays in to an sorted array as well.
* arr1(3, 4, 7, 9), arr2(5, 8, 9, 10) after concated: arr3(3, 4, 5, 7, 8, 9, 9, 10)
* @param1 : <array> List1 : the 1st sorted array
* @param2 : <array> List2 : the 2nd sorted array
* @param3 : <array> List3 : the concatend of 1st and 2nd array (in a sorted condition of course)
* @param4 : <boolean> Transform: TRUE belong to 'transformation' otherwise belong to 'inversing'
* @return : List3
* @effect : none
**}
function ConcatArray(List1, List2, List3: TArrayInt; Transform: Boolean): TArrayInt;
var
List1Index, List2Index, List3Index, I: Integer;
begin
List1Index := 0;
List2Index := 0;
List3Index := 0;
while (List1Index < Length(List1)) AND (List2Index < Length(List2)) do begin
if Transform then begin
if Compare(List1[List1Index], List2[List2Index]) then begin
List3[List3Index] := List1[List1Index];
Inc(List1Index);
end else begin
List3[List3Index] := List2[List2Index];
Inc(List2Index);
end;
end else begin
if Buffer[List1[List1Index]] < Buffer[List2[List2Index]] then begin
List3[List3Index] := List1[List1Index];
Inc(List1Index);
end else begin
List3[List3Index] := List2[List2Index];
Inc(List2Index);
end;
end;
Inc(List3Index);
end; { end while }
if List1Index >= Length(List1) then begin
for I := List2Index to Length(List2) - 1 do begin
List3[List3Index] := List2[I];
Inc(List3Index);
end;
end;
if List2Index >= Length(List2) then begin
for I := List1Index to Length(List1) - 1 do begin
List3[List3Index] := List1[I];
Inc(List3Index);
end;
end;
Result := List3;
end;
{**
* This function is used to slice an array from 'from' to 'max' index (it isn't simliar as substr).
* Is used for SortString algorithm due to the natural of this algorithm to divide
* recursively an array to be sorted.
* @Param 1 : <array> Arr : Array being sliced
* @Parm 2 : <integer> From, Max: Slice array from 'From' index to 'Max' index
* @Return : <array> Sliced Array
* @Effect : None
* arr[0, 2, 4, 6, 2, 9, 4, 5]: SliceArray(Arr, 2, 6) would return 4, 6, 2, 9 (4 wouldn't included
* since would be used as 'from' in the next Slicing (Upper sliced will be excluded) )
**}
function SliceArray(Arr: TArrayInt; From, Max: Integer): TArrayInt;
var
Half, I: LongInt;
NewArr: TArrayInt;
begin
Half := Max - From;
SetLength(NewArr, Half);
for I := 0 to Half - 1 do begin
NewArr[I] := Arr[From];
Inc(From);
end;
Result := NewArr;
end;
{** This is used to sort string not integer.
* @param1 : <array> : Unsorted array
* @param2 : <boolean> : Transform : TRUE for 'transformation' sorting owtherwise for 'inverse' sorting.
* @return : <array> : a sorted list
* @effect : <array> : Unsorted (parameter) will be in a sorted condition.
**}
function SortString(Unsorted: TArrayInt; Transform: Boolean): TArrayInt;
var
Cent: Integer;
First, Second: TArrayInt;
begin
if Length(Unsorted) > 1 then begin
Cent := Length(Unsorted) div 2;
First := SortString(SliceArray(Unsorted, 0, Cent), Transform);
Second := SortString(SliceArray(Unsorted, Cent, Length(Unsorted)), Transform);
Result := ConcatArray(First, Second, Unsorted, Transform);
end else begin
Result := Unsorted;
end;
end;
function ArraySearch(FChr: Char): Integer;
var
I, Found: Integer;
begin
for I := 1 to IntFileSize do begin
if FChr = Buffer2[I] then begin
Found := I - 1;
Buffer2[I] := Chr($00);
Break;
end;
end;
Result := Found;
end;
function BWTTransform(): String;
var
I, N: Integer;
Ranged: TArrayInt;
Last: String;
begin
N := IntFileSize;
SetLength(Ranged, N);
for I := 0 to N - 1 do begin
Ranged[I] := I;
end;
SortString(Ranged, TRUE); { Ranged now in a sorted array }
for I := 0 to N - 1 do begin
Last := Last + Copy(Rotate(Buffer, Ranged[I]), N, 1);
end;
Result := Last;
end;
function BWTReversing(): String;
var
FirstColumn, LastColumn, Vector: TArrayInt;
I, Index: Integer;
Last: String;
begin
SetLength(FirstColumn, IntFileSize);
SetLength(LastColumn, IntFileSize);
SetLength(Vector, IntFileSize);
Buffer2 := Buffer;
for I := 0 to IntFileSize - 1 do begin
LastColumn[I] := I; { containts indicies 0 - n}
end;
{ FirstColumn now sorted in lexicographically. Remember its indicies = values.
Only sort the character not string }
FirstColumn := SortString(LastColumn, FALSE);
// Creating vector
for I := 0 to IntFileSize - 1 do begin
Vector[I] := ArraySearch(Buffer[FirstColumn[I]]);
end;
// END_OF_FILE must be always in the last index since it's chr($ff) in the original text
Index := FirstColumn[I - 1];
for I := 0 to IntFileSize - 1 do begin
Index := Vector[Index];
Last := Last + Buffer[Index]; {Buffer = LastColumn. LastColumn has been sorted. So, don't use it}
end;
Result := Last;
end;
procedure FILE_CORRUPT_ERROR(Method : String);
begin
MessageDlg('It is not a/an ' + Method + ' file type or file may be corrupt. Decompression terminated!', MtERROR, [MbOK], 0);
end;
{**
* This procedure is used to set what grid will be using (ex: compress or decomress
* @Param 1 : <string> WhatType : compression or decompress
* @Return : None
* @Effect : Grid will looks like a dynamic grid
**}
procedure TFrmMAIN.GridTitle(WhatType: String);
var
I, J: Integer;
begin
{ Tab's Title Defenition Cells[Column, Rows] }
if WhatType = 'compression' then begin
StringGrid1.Cells[0, 0] := 'Algorithm';
StringGrid1.Cells[1, 0] := 'File Name';
StringGrid1.Cells[2, 0] := 'Original Size';
StringGrid1.Cells[3, 0] := 'After Compressed';
StringGrid1.Cells[4, 0] := 'Compression Ratio';
StringGrid1.Cells[5, 0] := 'Time Consuming';
end else begin
StringGrid1.ColCount := 5;
StringGrid1.ColWidths[1] := 250;
StringGrid1.Cells[0, 0] := 'Algorithm';
StringGrid1.Cells[1, 0] := 'File Name';
StringGrid1.Cells[2, 0] := 'Compressed Size';
StringGrid1.Cells[3, 0] := 'Original Size';
StringGrid1.Cells[4, 0] := 'Time Consuming';
end;
{ clear string grid }
for I := 1 to StringGrid1.RowCount do begin
for J := 0 to StringGrid1.ColCount do begin
StringGrid1.Cells[J, I] := '';
end;
end;
end;
procedure TFrmMAIN.CompressActive();
begin
DecompressGridCounter := 1;
OpenDialogType := True; { use openDialog1 }
Settings1.Enabled := True; { dictionary change is available }
GridTitle('compression'); { the grid's column title }
Decompression1.Checked := False;
Compression1.Checked := True;
{ compression and decompression buttons state }
CompressLZW.Enabled := True;
CompressAC.Enabled := True;
CompressRLEBWT.Enabled := True;
DecompressLZW.Enabled := False;
DecompressAC.Enabled := False;
DecompressRLEBWT.Enabled := False;
end;
procedure TFrmMAIN.DecompressActive();
begin
CompressGridCounter := 1;
OpenDialogType := False;
Settings1.Enabled := False;
GridTitle('decompression');
Decompression1.Checked := True;
Compression1.Checked := False;
CompressLZW.Enabled := False;
CompressAC.Enabled := False;
CompressRLEBWT.Enabled := False;
DecompressLZW.Enabled := True;
DecompressAC.Enabled := True;
DecompressRLEBWT.Enabled := True;
end;
{**
* This function is used to identify the file type for decompressing file.
* And that file types is just known for naming the decoded stream while decoding.
* It assumes the maximum of extention's length is 4 characters.
* @Param 1 : <string> Fname: File name taken from buffer
* @Return : <string> : the file type's name
* @Effect : None
**}
function KnownFileType(Fname: String): String;
var
Exp : TStringList;
begin
Exp := Explode('.', Fname );
Result := Exp[1];
end;
{** This procedure is used to open a file to be compressed or decompressed
* accept to 'state', OpenDialogType. True for compression and False for
* decompression. Is available for LZW, AC, and RLE+BWT. 'BUFFER' is the key
**}
procedure TFrmMAIN.OpenFile();
var
FH: TextFile;
Hold: Char;
I: Integer;
begin
{ compression opendialog }
if OpenDialogType then begin
CompressSavingPath := frmOPTION.TxtSaveCompressed.Text;
if DirectoryExists(CompressSavingPath) then begin
if OpenDialog1.Execute then begin
StrFileName := OpenDialog1.FileName;
{ add EOF for BWT indicator. It's also help for AC }
AssignFile(FH, StrFileName);
Reset( FH );
while not EOF( FH ) do begin
Read( FH, Hold );
end;
if Hold <> END_OF_FILE then begin
Append(FH);
Write(FH, END_OF_FILE);
end;
CloseFile(FH);
{ read to buffer }
AssignFile(FileHandling, StrFileName);
Reset(FileHandling, 1);
IntFileSize := FileSize(FileHandling);
repeat
BlockRead(FileHandling, Buffer, SizeOf(Buffer), NumRead);
until (NumRead = 0);
CloseFile(FileHandling);
{ START PLAY WITH ARITHMETIC CODING BY CREATING A MODEL }
// Set first frequency to zero
for I := 0 to 255 do begin
Frequency[Chr(I)] := 0;
end;
// count symbols frequency
for I := 0 to IntFileSize - 1 do begin
Frequency[Buffer[I]] := Frequency[Buffer[I]] + 1;
end;
// rescale the count. Will cause upper bounds of symbol < the total symbols count
Factor := Ceil(IntFileSize / Pow(2, 14));
// If a non-zero count become zero, make it one. Thank you Michael
TotalScaled := 0;
for I := 0 to 255 do begin
if Frequency[Chr(I)] > Factor then begin
Frequency[Chr(I)] := Floor( Frequency[Chr(I)]/Factor );
end else if Frequency[Chr(I)] <> 0 then begin
Frequency[Chr(I)] := 1;
end;
TotalScaled := TotalScaled + Frequency[Chr(I)];
end;
// Build model which only contain Low and High
BuildProbabilities(SymbolLow, SymbolHigh);
{ CREATING MODEL END HERE }
// Write the file information
LblFileName.Caption := ExtractFileName(StrFileName);
LblFileType.Caption := KnownFileType(ExtractFileName(StrFileName));
LblFileSize.Caption := IntToStr(IntFileSize) + ' bytes';
LblFileSource.Caption := StrFileName;
end;
end else begin
MessageDlg('Define first the compressed/decompressed path target from the option menu.', MtWarning, [MbOK], 0);
end;
end else begin { decompress opendialog }
DecompressSavingPath := frmOPTION.TxtSaveDecompressed.Text;
if DirectoryExists(DecompressSavingPath) then begin
if OpenDialog2.Execute then begin
StrFileName := OpenDialog2.FileName;
AssignFile(FileHandling, StrFileName);
Reset(FileHandling, 1);
IntFileSize := FileSize(FileHandling);
repeat
BlockRead(FileHandling, Buffer, SizeOf(Buffer), NumRead);
until (NumRead = 0);
CloseFile(FileHandling);
// write the file information
LblFileName.Caption := ExtractFileName(StrFileName);
LblFileType.Caption := KnownFileType(ExtractFileName(StrFileName));
LblFileSize.Caption := IntToStr(IntFileSize) + ' bytes';
LblFileSource.Caption := StrFileName;
end;
end else begin
MessageDlg('Define first the compressed/decompressed path target from the option menu.', MtWarning, [MbOK], 0);
end;
end;
end;
{** This procedure is used to save the compressed or decompressed file manually
* accept two properties: 'EncodedStream' and 'DecodedStream'.
* Is available for LZW, AC, and RLE+BWT.
**}
procedure TFrmMAIN.SaveAs();
var
Fout: TextFile;
I: Integer;
begin
if OpenDialogType then begin
if SaveDialog1.Execute then begin
AssignFile(Fout, SaveDialog1.FileName);
ReWrite(Fout);
for I := 1 to Length(EncodedStream) do begin
Write(Fout, EncodedStream[I]);
end;
CloseFile(Fout);
SaveAs1.Enabled := False;
end;
end else begin
if SaveDialog2.Execute then begin
AssignFile(Fout, SaveDialog2.FileName + '.txt');
ReWrite(Fout);
for I := 1 to Length(DecodedStream) do begin
Write(Fout, DecodedStream[I]);
end;
CloseFile(Fout);
SaveAs1.Enabled := False;
end;
end;
end;
procedure TFrmMain.SaveAutomatically(Res, Properties: String; Compress: Boolean);
var
Exp: TStringList;
Fout: TextFile;
I: Integer;
begin
CompressSavingPath := frmOPTION.TxtSaveCompressed.Text;
DecompressSavingPath := frmOPTION.TxtSaveDecompressed.Text;
Exp := Explode('.', ExtractFileName(StrFileName));
if DirectoryExists(CompressSavingPath) and DirectoryExists(DecompressSavingPath) then begin
if Compress then begin
AssignFile(Fout, CompressSavingPath + '\' + Exp[0] + '.' + Properties);
Rewrite(Fout);
for I := 1 to Length(Res) do begin
Write(Fout, Res[I]);
end;
CloseFile(Fout);
MessageDlg('Saving the compressed file is successfully in ' + CompressSavingPath, MtInformation, [MbOK], 0);
end else begin
AssignFile(Fout, DecompressSavingPath + '\' + Exp[0] + '.' + Properties + '.' + 'txt');
Rewrite(Fout);
for I := 1 to Length(Res) do begin
Write(Fout, Res[I]);
end;
CloseFile(Fout);
MessageDlg('Saving the Decompressed file is successfully in ' + DecompressSavingPath, MtInformation, [MbOK], 0);
end;
end else begin
MessageDlg('Automatic saving is failed. Save as it manually or set the new saving path from the option menu', MtError, [MbOK], 0);
end;
end;
{ write ratio in percent (%) }
function WriteRatio(Ratio: double):String;
begin
if Ratio < 1 then begin
WriteRatio := '0' + FormatFloat('#.##', Ratio) + '%';
end else begin
WriteRatio := FormatFloat('#.##', Ratio) + '%';
end;
end;
{ # --------------------------- END FOR ALL PROPERTIES ---------------------- #}
{ # --------------------- START FOR IMPLEMENTING OBJECTS --------------------- #}
procedure TfrmMAIN.FormCreate(Sender: TObject);
begin
ShowHint := True;
OpenDialogType := True;
CompressGridCounter := 1;
DecompressGridCounter := 1;
SetDictionaryLength := 2048;
SetBitsLength := 11;
GridTitle('compression');
{ Disable all components }
DecompressLZW.Enabled := False;
DecompressAC.Enabled := False;
DecompressRLEBWT.Enabled := False;
SaveAs1.Enabled := False;
end;
{ LZW Algorithm Compression }
procedure TfrmMAIN.CompressLZWClick(Sender: TObject);
var
I, J, K, Bits, OutputIndex, LastDictIndex: Integer;
CurrentChars, NextChar, ConcatStr, Header, Codeword: String;
{ counting the elapsed time }
Elapsed: String;
Start, Stop: TDateTime;
begin
Loading.Caption := 'Compressing...';
{ begin here to estimate the complexity (time complexity and running time) of
this LZW's encoding algorithm }
Start := Now;
{ Dictionary can be arbitary length: 8, 9, 10, 11 or 12 bits | 256, 512, 1024, 2048, 4096 }
SetLength(Dictionary, SetDictionaryLength);
Bits := SetBitsLength;
{ inisialization a dictionary 0 - 255 }
for I := 0 to DEFAULT_ASCII_SIZE do begin
Dictionary[I] := Chr(I);
end;
LastDictIndex := 256;
J := 0;
CurrentChars := SubStr(Buffer, 1, 1);
while J < IntFileSize do begin
NextChar := Buffer[J + 1];
ConcatStr := CurrentChars + NextChar;
if IsInDictionary(ConcatStr) then begin
CurrentChars := ConcatStr;
end else begin
OutputIndex := GetIndex(CurrentChars);
Codeword := Codeword + BitPadding(DecimalToBiner(OutputIndex), Bits, 'LEFT');
if LastDictIndex < Length(Dictionary) then begin
Dictionary[LastDictIndex] := ConcatStr;
end;
CurrentChars := NextChar;
Inc(LastDictIndex);
end;
if (J = IntFileSize - 1) then begin
OutputIndex := GetIndex(CurrentChars);
Codeword := Codeword + BitPadding(DecimalToBiner(OutputIndex), Bits, 'LEFT');
end;