+ #define DECOMPRESS_BUF_SIZE 1024
+ uint8_t outbuf[DECOMPRESS_BUF_SIZE];
+ uint8_t inbuf[DECOMPRESS_BUF_SIZE];
+ int32_t ret;
+
+ z_stream compressed_fpga_stream;
+
+ // initialize zlib structures
+ compressed_fpga_stream.next_in = inbuf;
+ compressed_fpga_stream.avail_in = 0;
+ compressed_fpga_stream.next_out = outbuf;
+ compressed_fpga_stream.avail_out = DECOMPRESS_BUF_SIZE;
+ compressed_fpga_stream.zalloc = fpga_deflate_malloc;
+ compressed_fpga_stream.zfree = fpga_deflate_free;
+ compressed_fpga_stream.opaque = Z_NULL;
+
+ ret = inflateInit2(&compressed_fpga_stream, 0);
+
+ do {
+ if (compressed_fpga_stream.avail_in == 0) {
+ compressed_fpga_stream.next_in = inbuf;
+ uint16_t i = 0;
+ do {
+ int32_t c = fgetc(infile);
+ if (!feof(infile)) {
+ inbuf[i++] = c & 0xFF;
+ compressed_fpga_stream.avail_in++;
+ } else {
+ break;
+ }
+ } while (i < DECOMPRESS_BUF_SIZE);
+ }
+
+ ret = inflate(&compressed_fpga_stream, Z_SYNC_FLUSH);
+
+ if (ret != Z_OK && ret != Z_STREAM_END) {
+ break;
+ }
+
+ if (compressed_fpga_stream.avail_out == 0) {
+ for (uint16_t i = 0; i < DECOMPRESS_BUF_SIZE; i++) {
+ fputc(outbuf[i], outfile);
+ }
+ compressed_fpga_stream.avail_out = DECOMPRESS_BUF_SIZE;
+ compressed_fpga_stream.next_out = outbuf;
+ }
+ } while (ret == Z_OK);
+
+ if (ret == Z_STREAM_END) { // reached end of input
+ uint16_t i = 0;
+ while (compressed_fpga_stream.avail_out < DECOMPRESS_BUF_SIZE) {
+ fputc(outbuf[i++], outfile);
+ compressed_fpga_stream.avail_out++;
+ }
+ fclose(outfile);
+ fclose(infile);
+ return(EXIT_SUCCESS);
+ } else {
+ fprintf(stderr, "Error. Inflate() returned error %i, %s", ret, compressed_fpga_stream.msg);
+ fclose(outfile);
+ fclose(infile);
+ return(EXIT_FAILURE);
+ }
+