Listing 11 Decode BAZ911-encoded file

/* ZAB.C
 * Contributed to Public Domain 9/93
 * by Thad Smith, Boulder Co.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "baz.h"

FILE        *inf, *outf; /* input, output files */

char        *error_msg[] = {
   "", "End of file before end of data\n",
   "Invalid input data\n", "CRC error\n",
"Conversion complete\n"};

unsigned char buf[8192];

/* Write data block to output file. */
/* ret value: 0 = OK, -1 = error     */
int dec_out (const char *out, size_t len) {
   fwrite ((const void *) out, 1, len, outf);
   return (ferror (outf) ? -1 : 0);
}

int main (int argc, char *argv[]) {

   char      line[100];  /* line buffer for header
                        * search                  */
   unsigned int n;       /* number of bytes read   */
   decode_stat s;        /* return status from
                        * encode/write           */

   if (argc!= 3) {
      puts ("ZAB - Convert BAZ911-encoded file to"
            "binary file");
      puts ("Usage: ZAB infile outfile");
      puts ("  infile= name of file in BAZ911 "
                                      "format");
      puts (" outfile= output binary file");
      return EXIT_FAILURE;
   }
   if ((inf = fopen (argv[1], "r")) == NULL) {
      fprintf (stderr, "Error opening input file: %s", argv[1]);
      return EXIT_FAILURE;
   }
   if ((outf = fopen (argv[2], "wb")) == NULL) {
      fprintf (stderr,"Error opening output file: %s", argv[2]);
      return EXIT_FAILURE;
   }
   dbaz_init (dec_out);
   do {
      if (!fgets (line, sizeof line, inf)) {
         fprintf (stderr, "BAZ911 starting flag not "
                  "found in %s\n", argv[1]);
         return EXIT_FAILURE;
      }
   }while (strncmp (line, "BAZ911:", 7) != 0);
   do {
      n = fread (buf, 1, sizeof buf, inf);
      s = dbaz_data (buf, n);
      if (s != DECR_OK) {
         if (s == DECR_END)
            break;
         if (s == -1)
            fprintf (stderr, "Error writing file\n");
         else
            fprintf (stderr, error_msg[s]);
         return EXIT_FAILURE;
      }
   } while (n > 0);
   if (ferror (inf)) {
      fprintf (stderr, "Error reading input file\n");
      return EXIT_FAILURE;
   }
   return EXIT_SUCCESS;
}

/* End of File */