2 * Copyright (C) 2009-2010 Andy Spencer <andy753421@gmail.com>
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 char *bunzip2(char *input, int input_len, int *output_len)
23 bz_stream *stream = g_new0(bz_stream, 1);
25 switch (BZ2_bzDecompressInit(stream, 0, 0)) {
26 case BZ_CONFIG_ERROR: g_error("the library has been mis-compiled");
27 case BZ_PARAM_ERROR: g_error("Parameter error");
28 case BZ_MEM_ERROR: g_error("insufficient memory is available");
29 //case BZ_OK: g_debug("success\n"); break;
30 //default: g_debug("unknown\n"); break;
34 int output_size = 512;
38 stream->next_in = input + stream->total_in_lo32;
39 stream->avail_in = input_len - stream->total_in_lo32;
41 output = g_realloc(output, output_size);
42 //g_debug("alloc %d\n", output_size);
43 stream->next_out = output + stream->total_out_lo32;
44 stream->avail_out = output_size - stream->total_out_lo32;
45 //g_debug("decompressing..\n"
49 // " avail_out = %u\n",
53 // stream->avail_out);
54 } while ((status = BZ2_bzDecompress(stream)) == BZ_OK && output_size < 1024*1024);
56 // g_debug("done with status %d = %d\n", status, BZ_STREAM_END);
58 *output_len = stream->total_out_lo32;
59 BZ2_bzDecompressEnd(stream);
63 int main(int argc, char **argv)
66 g_print("usage: %s <input> <output>\n", argv[0]);
70 FILE *input = fopen(argv[1], "r");
71 FILE *output = fopen(argv[2], "w+");
72 if (!input) g_error("error opening input");
73 if (!output) g_error("error opening output");
77 char *buf = g_malloc(24);
80 //g_debug("reading header\n");
81 if (!fread (buf, 24, 1, input))
82 g_error("error reading header");
83 if (!fwrite(buf, 24, 1, output))
84 g_error("error writing header");
86 //g_debug("reading body\n");
87 while ((st = fread(&size, 1, 4, input))) {
88 //g_debug("size=%08x\n", size);
89 //g_debug("read %u bytes\n", st);
90 //fwrite(&size, 1, 4, output); // DEBUG
91 size = ABS(g_ntohl(size));
94 //g_debug("size = %x\n", size);
95 if (size > 20*1024*1024)
96 g_error("sanity check failed, buf is to big: %d", size);
97 buf = g_realloc(buf, size);
98 if (!fread(buf, size, 1, input))
99 g_error("error reading data");
100 //fwrite(buf, 1, size, output); // DEBUG
103 char *dec = bunzip2(buf, size, &dec_len);
104 // g_debug("decompressed %u bytes\n", dec_len);
105 if (!fwrite(dec, 1, dec_len, output))
106 g_error("error writing data");