]> git.llucax.com Git - z.facultad/75.06/jacu.git/blob - src/statichuff/statichuff.c
arreglos minimos, saco los printf feos
[z.facultad/75.06/jacu.git] / src / statichuff / statichuff.c
1
2 #include "statichuff.h"
3 #include <stdlib.h>
4
5 void putbit(char bit, char restart, char flush, FILE *fp)
6 {
7         static unsigned long int bits_buffer = 0;
8         static unsigned char bits_used = 0;
9         int i;
10
11         /* me obligan a emitir el output */
12         if ((flush == 1) && (bits_used > 0)) {
13                 bits_buffer = bits_buffer << ((sizeof(unsigned long int)*8) - bits_used);
14                 fwrite(&bits_buffer,sizeof(unsigned long int),1,fp);
15                 bits_buffer = 0;
16                 bits_used = 0;
17                 return;
18         }       
19         /* me indican que comienza un nuevo output */
20         if (restart) {
21                 bits_buffer = 0;
22                 bits_used = 0;
23         }                       
24         /* inserto el bit en el buffer */       
25         bits_buffer = bits_buffer << 1;
26         bits_buffer |= bit;
27         bits_used++;
28         
29         /* lleno el buffer, escribo */
30         if (bits_used == 32) {
31                 fwrite(&bits_buffer,sizeof(unsigned long int),1,fp);
32                 bits_buffer = 0;
33                 bits_used = 0;
34         }       
35         return;
36 }
37
38 void shuff_cpynode(SHUFFNODE *node1, SHUFFNODE *node2)
39 {
40         node1->symbol = node2->symbol;
41         node1->freq = node2->freq;
42         node1->lchild = node2->lchild;
43         node1->rchild = node2->rchild;  
44 }
45
46 int shuff_compnode(SHUFFNODE *node1, SHUFFNODE *node2)
47 {       
48         if (node1->freq < node2->freq) return 1;
49         if (node1->freq > node2->freq) return -1;
50         return 0;
51 }
52
53 int shuff_rescalefreq(t_freq *freqtable)
54
55         int i;
56         t_freq totalfreq = 0;
57         
58         /* Divido por la mitad las frecuencias, asegurando de no perder */
59         /* frequencias en 1, por ello le sumo 1 antes de partir */
60         for (i = 0; i < 256; i++) {             
61                 freqtable[i] = (freqtable[i] << 2) | 1;
62                 totalfreq += freqtable[i];
63         }
64         
65         return totalfreq;
66 }
67
68 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
69 {
70         /* Locals */    
71         FILE *fp;
72         t_freq sumfreq = 0;
73         int i,symbol;
74         
75         /* Inicializamos la tabla de frecuencias */     
76         for (i = 0; i < 256; ++i) freqtable[i] = 0;
77                 
78         /* Abrimos el file */
79         if ((fp = fopen(inputfile,"rb")) == NULL) return 0;
80         while (!feof(fp)) {             
81                 /* Contamos las frecuencias */          
82                 symbol = fgetc(fp);
83                 if (symbol == EOF) continue;
84                 
85                 freqtable[symbol]++;            
86                 ++sumfreq;
87                                 
88                 /* Si llegue al tope de freq acumulada, halve em */
89                 if (sumfreq == 14930352) 
90                         sumfreq = shuff_rescalefreq(freqtable);
91         }
92         
93         fclose(fp);
94         return 1;       
95 }
96
97 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
98 {
99         int i,j = 0,nonzero = 0;        
100         SHUFFNODE *inputlist;
101         
102         /* Calculo cuantas frequencias > 0 hay y creo la tabla */
103         for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
104         inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
105                 
106         /* Cargo la inputlist del huffman solo con freqs > 0 */
107         for (i = 0; i < 256; ++i)
108                 if (freqtable[i] > 0) {                 
109                         inputlist[j].symbol = i;
110                         inputlist[j].freq = freqtable[i];
111                         inputlist[j].lchild = NULL;
112                         inputlist[j].rchild = NULL;                     
113                         j++;
114                 }
115                 
116         *nonzerofreqs = nonzero;
117         return inputlist;
118 }
119
120 SHUFFNODE *shuff_buildtree(SHUFFNODE *list, int listcount)
121 {
122         SHUFFNODE *lastsymbol = list+(listcount-1);
123         SHUFFNODE *node1,*node2,*fictnode;
124
125         /* Ordenamos inicialmente la inputlist para tomar las dos freqs min */
126         while (lastsymbol > list) {             
127                 /* Ordeno la lista por frecuencia descendente */
128                 qsort(list,listcount,sizeof(SHUFFNODE),shuff_compnode);                         
129                 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
130                 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
131                 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
132                 shuff_cpynode(node1,lastsymbol-1);
133                 shuff_cpynode(node2,lastsymbol);                
134                 lastsymbol -= 1;
135                 /* Nodo ficticio con la suma de las probs y los ptros a childs */
136                 lastsymbol->symbol = 256;
137                 lastsymbol->freq = node1->freq + node2->freq;
138                 lastsymbol->lchild = node1;
139                 lastsymbol->rchild = node2;
140                 --listcount;
141         }
142                 
143         /* Devuelvo el puntero a la raiz del arbol de huffman */
144         return lastsymbol;
145 }
146
147 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
148 {
149         int i,j;
150         unsigned short int auxcode;
151         unsigned char bit;
152         
153         for (i = 0; i < 256; ++i) {
154                 if (codetable[i].codelength > 0) {
155                         auxcode = codetable[i].code;                    
156                         printf("Symbol:%i  Freq: %li  Code:",i,freqtable[i]);
157                         for (j = codetable[i].codelength-1; j >= 0; --j) {
158                                 auxcode = codetable[i].code;                    
159                                 auxcode = auxcode >> j;
160                                 bit = auxcode & 1;                              
161                                 printf("%i",bit);
162                         }
163                         printf("  Length:%i\n",codetable[i].codelength);
164                 }               
165         }
166 }
167
168 void shuff_zerocodes(SHUFFCODE *table)
169 {
170         int i;
171         
172         /* Inicializo los codigos prefijos */   
173         for (i = 0; i < 256; ++i) {
174                 table[i].code = 0;
175                 table[i].codelength = 0;
176         }
177 }
178
179 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
180 {
181         if (node->symbol < 256) {
182                 /* Guardo el codigo en la tabla */
183                 table[node->symbol].code = code;
184                 table[node->symbol].codelength = level;         
185         }
186         else {
187                 code = code << 1;
188                 shuff_buildcodes(table,node->lchild,level+1,code);
189                 code |= 1;
190                 shuff_buildcodes(table,node->rchild,level+1,code);
191         }
192 }
193
194
195
196 int shuff_encode_symbols(t_freq *ftable, SHUFFCODE *ctable, char* inputfile, char *outputfile) {
197
198         FILE *fpsource,*fpdest;
199         int symbol,i;
200         unsigned long int sourcesize;
201         char bit;
202         SHUFFCODE symbolcode;
203                 
204         /* Abrimos el file */
205         if ((fpsource = fopen(inputfile,"rb")) == NULL) return 0;
206         if ((fpdest = fopen(outputfile,"wb")) == NULL) return 0;
207                 
208         /* Guardamos el size el archivo original e inputlist como header */
209         fseek(fpsource,0,SEEK_END);
210         sourcesize = ftell(fpsource);
211         fwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
212         fwrite(ftable,sizeof(t_freq),256,fpdest);
213         
214         /* Encodeo */
215         fseek(fpsource,0,SEEK_SET);
216         while (!feof(fpsource)) {
217                 /* Levanto un symbolo (byte) */         
218                 symbol = fgetc(fpsource);
219                 if (symbol == EOF) continue;
220                 
221                 /* Cargamos el codigo y lo emitimos */
222                 symbolcode = ctable[symbol];
223                 for (i = symbolcode.codelength; i > 0; --i) {
224                         bit = (symbolcode.code >> (i-1)) & 1;
225                         putbit(bit,0,0,fpdest);
226                 }               
227         }
228         
229         /* Hacemos un flush de lo que haya quedado en el buffer de salida */
230         putbit(0,0,1,fpdest);
231         fclose(fpsource);
232         fclose(fpdest);
233         return 1;       
234 }
235
236 int shuff_encode_file(char *inputfile, char *outputfile)
237 {
238         /* Locals */
239         t_freq *freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
240         SHUFFNODE *inputlist;
241         SHUFFNODE *codetree;
242         SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
243         int freqcount = 0,i;
244         
245         /* Armamos la tabla de frecuencias */
246         if (!shuff_scanfreq(inputfile,freqtable)) return -1;
247         
248         /* Armo el input list y genero el arbol de huffman */
249         inputlist = shuff_buildlist(freqtable, &freqcount);
250         codetree = shuff_buildtree(inputlist,freqcount);
251
252         /* Armo la tabla de codigos prefijos para el encoder */
253         shuff_zerocodes(codetable);
254         shuff_buildcodes(codetable,codetree,0,0);
255         shuff_printcodes(codetable,freqtable);
256
257         /* Encodeo byte per byte */
258         shuff_encode_symbols(freqtable,codetable,inputfile,outputfile);
259 }
260
261 int shuff_decode(char *inputfile, char *outputfile)
262 {
263         SHUFFNODE *inputlist;
264         SHUFFNODE *codetree;
265         t_freq *ftable = (t_freq*)malloc(sizeof(t_freq)*256);
266         unsigned long int bytesleft;
267         FILE *fpsource;
268         FILE *fpdest;
269         int i,freqcount = 0;
270         
271         /* Levanto cuantos bytes decodeo y la freq table */
272         if ((fpsource = fopen(inputfile,"rb")) == NULL) return 0;
273         if ((fpdest = fopen(outputfile,"wb")) == NULL) return 0;
274         fread(&bytesleft,sizeof(unsigned long int),1,fpsource);
275         fread(ftable,sizeof(unsigned long int),256,fpsource);
276         inputlist = shuff_buildlist(ftable, &freqcount);
277         codetree = shuff_buildtree(inputlist,freqcount);
278                 
279         fclose(fpsource);
280         fclose(fpdest);
281         
282         
283 }
284
285 int main(int argc, char* argv[])
286 {       
287         if (argc == 1) return -1;
288                 
289         /* Comprimo */
290         shuff_encode_file(argv[1],"output.shf");        
291
292         /* Decodeo */
293         shuff_decode("output.shf","decoded.dat");
294         
295         return 0;
296 }