1 /*
2
3 Copyright (C) 2015-2018 Night Dive Studios, LLC.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 */
19 // LZWTEST.C - Computes compression ratio for data
20 // Rex E. Bradford
21
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "lzw.h"
26
main(void)27 void main(void) {
28 StandardFileReply reply;
29 SFTypeList typeList;
30 short filenum;
31 Handle resHdl, exHdl;
32 Ptr compBuff;
33 long len, clen, exlen;
34 float ratio;
35
36 // Open a resource file.
37
38 printf("Select the LzwTest resource file...\n\n");
39
40 typeList[0] = 'rsrc';
41 StandardGetFile(nil, 1, typeList, &reply);
42 if (reply.sfGood) {
43 filenum = FSpOpenResFile(&reply.sfFile, fsRdWrPerm);
44 if (filenum == -1) {
45 printf("Couldn't open the resource file.\n");
46 exit(-1);
47 }
48
49 // Get the text resource from the file and its length.
50
51 resHdl = Get1Resource('TEXT', 128);
52 if (resHdl == NULL) {
53 printf("Couldn't get the text resource.\n");
54 exit(-2);
55 }
56 len = GetHandleSize(resHdl);
57 HLock(resHdl);
58
59 // Allocate buffer to hold compressed data.
60
61 compBuff = malloc(len);
62 if (compBuff == NULL) {
63 printf("Couldn't allocate compBuff.\n");
64 exit(-3);
65 }
66
67 // Allocate handle to hold expanded data.
68
69 exHdl = NewHandle(len + 100); // Just to be safe
70 if (exHdl == NULL) {
71 printf("Couldn't allocate exHdl.\n");
72 exit(-4);
73 }
74 HLock(exHdl);
75
76 // Compress into bit bucket
77
78 LzwInit();
79 clen = LzwCompressBuff2Buff(*resHdl, len, compBuff, len);
80 exlen = LzwExpandBuff2Buff(compBuff, *exHdl, 0, 0);
81 LzwTerm();
82
83 // Add the expanded handle to the resource file, for later comparison.
84
85 resHdl = Get1Resource('TEXT', 1000); // Delete if already there.
86 if (resHdl != NULL) {
87 RmveResource(resHdl);
88 DisposeHandle(resHdl);
89 }
90 HUnlock(exHdl);
91 SetHandleSize(exHdl, exlen);
92 AddResource(exHdl, 'TEXT', 1000, "Expanded");
93 ChangedResource(exHdl);
94 WriteResource(exHdl);
95
96 CloseResFile(filenum);
97
98 // Compute compression ratio
99
100 ratio = (float)len / (float)clen;
101
102 // Issue report
103
104 printf("Org length: %d compressed length: %d comp ratio: %f:1\n", len,
105 clen, ratio);
106 printf("Expanded length: %d\n", exlen);
107 printf("\nCompare the original and expanded resources with ResEdit.\n");
108 }
109 exit(0);
110 }
111