  char * unescape(char * dest, const char * src)
  {
    while (*src) {
      if (*src == '\\' && src[1]) {
	++src;
	switch (*src) {
	case 'n': *dest = '\n'; break;
	case 'r': *dest = '\r'; break;
	case 't': *dest = '\t'; break;
	case 'f': *dest = '\f'; break;
	case 'v': *dest = '\v'; break;
	default: *dest = *src;
	}
      } else {
	*dest = *src;
      }
      ++src;
      ++dest;
    }
    *dest = '\0';
    return dest;
  }


Fix segfault in src/bin/jp2/opj_decompress.c due to uninitialized pointer (fixes #1368) (#1369)

int main(int argc, char **argv)
{
    opj_decompress_parameters parameters;           /* decompression parameters */

    OPJ_INT32 num_images, imageno;
    img_fol_t img_fol;
    dircnt_t *dirptr = NULL;
    int failed = 0;
    OPJ_FLOAT64 t, tCumulative = 0;
    OPJ_UINT32 numDecompressedImages = 0;
    OPJ_UINT32 cp_reduce;

    /* set decoding parameters to default values */
    set_default_parameters(&parameters);

    /* Initialize img_fol */
    memset(&img_fol, 0, sizeof(img_fol_t));

    /* parse input and get user encoding parameters */
    if (parse_cmdline_decoder(argc, argv, &parameters, &img_fol) == 1) {
        failed = 1;
        goto fin;
    }

    cp_reduce = parameters.core.cp_reduce;
    if (getenv("USE_OPJ_SET_DECODED_RESOLUTION_FACTOR") != NULL) {
        /* For debugging/testing purposes, do not set the cp_reduce member */
        /* if USE_OPJ_SET_DECODED_RESOLUTION_FACTOR is defined, but used */
        /* the opj_set_decoded_resolution_factor() API instead */
        parameters.core.cp_reduce = 0;
    }

    /* Initialize reading of directory */
    if (img_fol.set_imgdir == 1) {
        int it_image;
        num_images = get_num_images(img_fol.imgdirpath);

        dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
        if (!dirptr) {
            destroy_parameters(&parameters);
            return EXIT_FAILURE;
        }
        /* Stores at max 10 image file names */
        dirptr->filename_buf = (char*)malloc(sizeof(char) *
                                             (size_t)num_images * OPJ_PATH_LEN);
        if (!dirptr->filename_buf) {
            failed = 1;
            goto fin;
        }

        dirptr->filename = (char**) malloc((size_t)num_images * sizeof(char*));

        if (!dirptr->filename) {
            failed = 1;
            goto fin;
        }
        for (it_image = 0; it_image < num_images; it_image++) {
            dirptr->filename[it_image] = dirptr->filename_buf + it_image * OPJ_PATH_LEN;
        }

        if (load_images(dirptr, img_fol.imgdirpath) == 1) {
            failed = 1;
            goto fin;
        }
        if (num_images == 0) {
            fprintf(stderr, "Folder is empty\n");
            failed = 1;
            goto fin;
        }
    } else {
        num_images = 1;
    }

    /*Decoding image one by one*/
    for (imageno = 0; imageno < num_images ; imageno++)  {
        opj_image_t* image = NULL;
        opj_stream_t *l_stream = NULL;              /* Stream */
        opj_codec_t* l_codec = NULL;                /* Handle to a decompressor */
        opj_codestream_index_t* cstr_index = NULL;

        if (!parameters.quiet) {
            fprintf(stderr, "\n");
        }

        if (img_fol.set_imgdir == 1) {
            if (get_next_file(imageno, dirptr, &img_fol, &parameters)) {
                fprintf(stderr, "skipping file...\n");
                destroy_parameters(&parameters);
                continue;
            }
        }

        /* read the input file and put it in memory */
        /* ---------------------------------------- */

        l_stream = opj_stream_create_default_file_stream(parameters.infile, 1);
        if (!l_stream) {
            fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n",
                    parameters.infile);
            failed = 1;
            goto fin;
        }

        /* decode the JPEG2000 stream */
        /* ---------------------- */

        switch (parameters.decod_format) {
        case J2K_CFMT: { /* JPEG-2000 codestream */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_J2K);
            break;
        }
        case JP2_CFMT: { /* JPEG 2000 compressed image data */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JP2);
            break;
        }
        case JPT_CFMT: { /* JPEG 2000, JPIP */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JPT);
            break;
        }
        default:
            fprintf(stderr, "skipping file..\n");
            destroy_parameters(&parameters);
            opj_stream_destroy(l_stream);
            continue;
        }

        if (parameters.quiet) {
            /* Set all callbacks to quiet */
            opj_set_info_handler(l_codec, quiet_callback, 00);
            opj_set_warning_handler(l_codec, quiet_callback, 00);
            opj_set_error_handler(l_codec, quiet_callback, 00);
        } else {
            /* catch events using our callbacks and give a local context */
            opj_set_info_handler(l_codec, info_callback, 00);
            opj_set_warning_handler(l_codec, warning_callback, 00);
            opj_set_error_handler(l_codec, error_callback, 00);
        }

        t = opj_clock();

        /* Setup the decoder decoding parameters using user parameters */
        if (!opj_setup_decoder(l_codec, &(parameters.core))) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to setup the decoder\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            failed = 1;
            goto fin;
        }

        if (parameters.num_threads >= 1 &&
                !opj_codec_set_threads(l_codec, parameters.num_threads)) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to set number of threads\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            failed = 1;
            goto fin;
        }

        /* Read the main header of the codestream and if necessary the JP2 boxes*/
        if (! opj_read_header(l_stream, l_codec, &image)) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            failed = 1;
            goto fin;
        }

        if (parameters.numcomps) {
            if (! opj_set_decoded_components(l_codec,
                                             parameters.numcomps,
                                             parameters.comps_indices,
                                             OPJ_FALSE)) {
                fprintf(stderr,
                        "ERROR -> opj_decompress: failed to set the component indices!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
        }

        if (getenv("USE_OPJ_SET_DECODED_RESOLUTION_FACTOR") != NULL) {
            /* For debugging/testing purposes, and also an illustration on how to */
            /* use the alternative API opj_set_decoded_resolution_factor() instead */
            /* of setting parameters.cp_reduce */
            if (! opj_set_decoded_resolution_factor(l_codec, cp_reduce)) {
                fprintf(stderr,
                        "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
        }

        if (!parameters.nb_tile_to_decode) {
            if (getenv("SKIP_OPJ_SET_DECODE_AREA") != NULL &&
                    parameters.DA_x0 == 0 &&
                    parameters.DA_y0 == 0 &&
                    parameters.DA_x1 == 0 &&
                    parameters.DA_y1 == 0) {
                /* For debugging/testing purposes, */
                /* do nothing if SKIP_OPJ_SET_DECODE_AREA env variable */
                /* is defined and no decoded area has been set */
            }
            /* Optional if you want decode the entire image */
            else if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
                                          (OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1,
                                          (OPJ_INT32)parameters.DA_y1)) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to set the decoded area\n");
                opj_stream_destroy(l_stream);
                opj_destroy_codec(l_codec);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }

            /* Get the decoded image */
            if (!(opj_decode(l_codec, l_stream, image) &&
                    opj_end_decompress(l_codec,   l_stream))) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to decode image!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
        } else {
            if (!(parameters.DA_x0 == 0 &&
                    parameters.DA_y0 == 0 &&
                    parameters.DA_x1 == 0 &&
                    parameters.DA_y1 == 0)) {
                if (!(parameters.quiet)) {
                    fprintf(stderr, "WARNING: -d option ignored when used together with -t\n");
                }
            }

            if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
            if (!(parameters.quiet)) {
                fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
            }
        }

        tCumulative += opj_clock() - t;
        numDecompressedImages++;

        /* Close the byte stream */
        opj_stream_destroy(l_stream);

        if (image->color_space != OPJ_CLRSPC_SYCC
                && image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
                && image->comps[1].dx != 1) {
            image->color_space = OPJ_CLRSPC_SYCC;
        } else if (image->numcomps <= 2) {
            image->color_space = OPJ_CLRSPC_GRAY;
        }

        if (image->color_space == OPJ_CLRSPC_SYCC) {
            color_sycc_to_rgb(image);
        } else if ((image->color_space == OPJ_CLRSPC_CMYK) &&
                   (parameters.cod_format != TIF_DFMT)) {
            color_cmyk_to_rgb(image);
        } else if (image->color_space == OPJ_CLRSPC_EYCC) {
            color_esycc_to_rgb(image);
        }

        if (image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
            if (image->icc_profile_len) {
                color_apply_icc_profile(image);
            } else {
                color_cielab_to_rgb(image);
            }
#endif
            free(image->icc_profile_buf);
            image->icc_profile_buf = NULL;
            image->icc_profile_len = 0;
        }

        /* Force output precision */
        /* ---------------------- */
        if (parameters.precision != NULL) {
            OPJ_UINT32 compno;
            for (compno = 0; compno < image->numcomps; ++compno) {
                OPJ_UINT32 precno = compno;
                OPJ_UINT32 prec;

                if (precno >= parameters.nb_precision) {
                    precno = parameters.nb_precision - 1U;
                }

                prec = parameters.precision[precno].prec;
                if (prec == 0) {
                    prec = image->comps[compno].prec;
                }

                switch (parameters.precision[precno].mode) {
                case OPJ_PREC_MODE_CLIP:
                    clip_component(&(image->comps[compno]), prec);
                    break;
                case OPJ_PREC_MODE_SCALE:
                    scale_component(&(image->comps[compno]), prec);
                    break;
                default:
                    break;
                }

            }
        }

        /* Upsample components */
        /* ------------------- */
        if (parameters.upsample) {
            image = upsample_image_components(image);
            if (image == NULL) {
                fprintf(stderr,
                        "ERROR -> opj_decompress: failed to upsample image components!\n");
                opj_destroy_codec(l_codec);
                failed = 1;
                goto fin;
            }
        }

        /* Force RGB output */
        /* ---------------- */
        if (parameters.force_rgb) {
            switch (image->color_space) {
            case OPJ_CLRSPC_SRGB:
                break;
            case OPJ_CLRSPC_GRAY:
                image = convert_gray_to_rgb(image);
                break;
            default:
                fprintf(stderr,
                        "ERROR -> opj_decompress: don't know how to convert image to RGB colorspace!\n");
                opj_image_destroy(image);
                image = NULL;
                break;
            }
            if (image == NULL) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to convert to RGB image!\n");
                opj_destroy_codec(l_codec);
                failed = 1;
                goto fin;
            }
        }

        /* create output image */
        /* ------------------- */
        switch (parameters.cod_format) {
        case PXM_DFMT:          /* PNM PGM PPM */
            if (imagetopnm(image, parameters.outfile, parameters.split_pnm)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case PGX_DFMT:          /* PGX */
            if (imagetopgx(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case BMP_DFMT:          /* BMP */
            if (imagetobmp(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#ifdef OPJ_HAVE_LIBTIFF
        case TIF_DFMT:          /* TIF(F) */
            if (imagetotif(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#endif /* OPJ_HAVE_LIBTIFF */
        case RAW_DFMT:          /* RAW */
            if (imagetoraw(image, parameters.outfile)) {
                fprintf(stderr,
                        "[ERROR] Error generating raw or yuv file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case RAWL_DFMT:         /* RAWL */
            if (imagetorawl(image, parameters.outfile)) {
                fprintf(stderr,
                        "[ERROR] Error generating rawl file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case TGA_DFMT:          /* TGA */
            if (imagetotga(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Error generating tga file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#ifdef OPJ_HAVE_LIBPNG
        case PNG_DFMT:          /* PNG */
            if (imagetopng(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Error generating png file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#endif /* OPJ_HAVE_LIBPNG */
        /* Can happen if output file is TIF(F) or PNG
         * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
        */
        default:
            fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
            failed = 1;
        }

        /* free remaining structures */
        if (l_codec) {
            opj_destroy_codec(l_codec);
        }

        /* free image data structure */
        opj_image_destroy(image);

        /* destroy the codestream index */
        opj_destroy_cstr_index(&cstr_index);

        if (failed) {
            (void)remove(parameters.outfile);    /* ignore return value */
        }
    }
fin:
    destroy_parameters(&parameters);
    if (failed && img_fol.imgdirpath) {
        free(img_fol.imgdirpath);
    }
    if (dirptr) {
        if (dirptr->filename) {
            free(dirptr->filename);
        }
        if (dirptr->filename_buf) {
            free(dirptr->filename_buf);
        }
        free(dirptr);
    }
    if (numDecompressedImages && !failed && !(parameters.quiet)) {
        fprintf(stdout, "decode time: %d ms\n",
                (int)((tCumulative * 1000.0) / (OPJ_FLOAT64)numDecompressedImages));
    }
    return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}

A flaw was found in the opj2_decompress program in openjpeg2 2.4.0 in the way it handles an input directory with a large number of files. When it fails to allocate a buffer to store the filenames of the input directory, it calls free() on an uninitialized pointer, leading to a segmentation fault and a denial of service.


int main(int argc, char **argv)
{
    opj_decompress_parameters parameters;           /* decompression parameters */

    OPJ_INT32 num_images, imageno;
    img_fol_t img_fol;
    dircnt_t *dirptr = NULL;
    int failed = 0;
    OPJ_FLOAT64 t, tCumulative = 0;
    OPJ_UINT32 numDecompressedImages = 0;
    OPJ_UINT32 cp_reduce;

    /* set decoding parameters to default values */
    set_default_parameters(&parameters);

    /* Initialize img_fol */
    memset(&img_fol, 0, sizeof(img_fol_t));

    /* parse input and get user encoding parameters */
    if (parse_cmdline_decoder(argc, argv, &parameters, &img_fol) == 1) {
        failed = 1;
        goto fin;
    }

    cp_reduce = parameters.core.cp_reduce;
    if (getenv("USE_OPJ_SET_DECODED_RESOLUTION_FACTOR") != NULL) {
        /* For debugging/testing purposes, do not set the cp_reduce member */
        /* if USE_OPJ_SET_DECODED_RESOLUTION_FACTOR is defined, but used */
        /* the opj_set_decoded_resolution_factor() API instead */
        parameters.core.cp_reduce = 0;
    }

    /* Initialize reading of directory */
    if (img_fol.set_imgdir == 1) {
        int it_image;
        num_images = get_num_images(img_fol.imgdirpath);

        dirptr = (dircnt_t*)calloc(1, sizeof(dircnt_t));
        if (!dirptr) {
            destroy_parameters(&parameters);
            return EXIT_FAILURE;
        }
        /* Stores at max 10 image file names */
        dirptr->filename_buf = (char*)malloc(sizeof(char) *
                                             (size_t)num_images * OPJ_PATH_LEN);
        if (!dirptr->filename_buf) {
            failed = 1;
            goto fin;
        }

        dirptr->filename = (char**) malloc((size_t)num_images * sizeof(char*));

        if (!dirptr->filename) {
            failed = 1;
            goto fin;
        }
        for (it_image = 0; it_image < num_images; it_image++) {
            dirptr->filename[it_image] = dirptr->filename_buf + it_image * OPJ_PATH_LEN;
        }

        if (load_images(dirptr, img_fol.imgdirpath) == 1) {
            failed = 1;
            goto fin;
        }
        if (num_images == 0) {
            fprintf(stderr, "Folder is empty\n");
            failed = 1;
            goto fin;
        }
    } else {
        num_images = 1;
    }

    /*Decoding image one by one*/
    for (imageno = 0; imageno < num_images ; imageno++)  {
        opj_image_t* image = NULL;
        opj_stream_t *l_stream = NULL;              /* Stream */
        opj_codec_t* l_codec = NULL;                /* Handle to a decompressor */
        opj_codestream_index_t* cstr_index = NULL;

        if (!parameters.quiet) {
            fprintf(stderr, "\n");
        }

        if (img_fol.set_imgdir == 1) {
            if (get_next_file(imageno, dirptr, &img_fol, &parameters)) {
                fprintf(stderr, "skipping file...\n");
                destroy_parameters(&parameters);
                continue;
            }
        }

        /* read the input file and put it in memory */
        /* ---------------------------------------- */

        l_stream = opj_stream_create_default_file_stream(parameters.infile, 1);
        if (!l_stream) {
            fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n",
                    parameters.infile);
            failed = 1;
            goto fin;
        }

        /* decode the JPEG2000 stream */
        /* ---------------------- */

        switch (parameters.decod_format) {
        case J2K_CFMT: { /* JPEG-2000 codestream */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_J2K);
            break;
        }
        case JP2_CFMT: { /* JPEG 2000 compressed image data */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JP2);
            break;
        }
        case JPT_CFMT: { /* JPEG 2000, JPIP */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JPT);
            break;
        }
        default:
            fprintf(stderr, "skipping file..\n");
            destroy_parameters(&parameters);
            opj_stream_destroy(l_stream);
            continue;
        }

        if (parameters.quiet) {
            /* Set all callbacks to quiet */
            opj_set_info_handler(l_codec, quiet_callback, 00);
            opj_set_warning_handler(l_codec, quiet_callback, 00);
            opj_set_error_handler(l_codec, quiet_callback, 00);
        } else {
            /* catch events using our callbacks and give a local context */
            opj_set_info_handler(l_codec, info_callback, 00);
            opj_set_warning_handler(l_codec, warning_callback, 00);
            opj_set_error_handler(l_codec, error_callback, 00);
        }

        t = opj_clock();

        /* Setup the decoder decoding parameters using user parameters */
        if (!opj_setup_decoder(l_codec, &(parameters.core))) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to setup the decoder\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            failed = 1;
            goto fin;
        }

        if (parameters.num_threads >= 1 &&
                !opj_codec_set_threads(l_codec, parameters.num_threads)) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to set number of threads\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            failed = 1;
            goto fin;
        }

        /* Read the main header of the codestream and if necessary the JP2 boxes*/
        if (! opj_read_header(l_stream, l_codec, &image)) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            failed = 1;
            goto fin;
        }

        if (parameters.numcomps) {
            if (! opj_set_decoded_components(l_codec,
                                             parameters.numcomps,
                                             parameters.comps_indices,
                                             OPJ_FALSE)) {
                fprintf(stderr,
                        "ERROR -> opj_decompress: failed to set the component indices!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
        }

        if (getenv("USE_OPJ_SET_DECODED_RESOLUTION_FACTOR") != NULL) {
            /* For debugging/testing purposes, and also an illustration on how to */
            /* use the alternative API opj_set_decoded_resolution_factor() instead */
            /* of setting parameters.cp_reduce */
            if (! opj_set_decoded_resolution_factor(l_codec, cp_reduce)) {
                fprintf(stderr,
                        "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
        }

        if (!parameters.nb_tile_to_decode) {
            if (getenv("SKIP_OPJ_SET_DECODE_AREA") != NULL &&
                    parameters.DA_x0 == 0 &&
                    parameters.DA_y0 == 0 &&
                    parameters.DA_x1 == 0 &&
                    parameters.DA_y1 == 0) {
                /* For debugging/testing purposes, */
                /* do nothing if SKIP_OPJ_SET_DECODE_AREA env variable */
                /* is defined and no decoded area has been set */
            }
            /* Optional if you want decode the entire image */
            else if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
                                          (OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1,
                                          (OPJ_INT32)parameters.DA_y1)) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to set the decoded area\n");
                opj_stream_destroy(l_stream);
                opj_destroy_codec(l_codec);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }

            /* Get the decoded image */
            if (!(opj_decode(l_codec, l_stream, image) &&
                    opj_end_decompress(l_codec,   l_stream))) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to decode image!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
        } else {
            if (!(parameters.DA_x0 == 0 &&
                    parameters.DA_y0 == 0 &&
                    parameters.DA_x1 == 0 &&
                    parameters.DA_y1 == 0)) {
                if (!(parameters.quiet)) {
                    fprintf(stderr, "WARNING: -d option ignored when used together with -t\n");
                }
            }

            if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
                opj_destroy_codec(l_codec);
                opj_stream_destroy(l_stream);
                opj_image_destroy(image);
                failed = 1;
                goto fin;
            }
            if (!(parameters.quiet)) {
                fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
            }
        }

        tCumulative += opj_clock() - t;
        numDecompressedImages++;

        /* Close the byte stream */
        opj_stream_destroy(l_stream);

        if (image->color_space != OPJ_CLRSPC_SYCC
                && image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
                && image->comps[1].dx != 1) {
            image->color_space = OPJ_CLRSPC_SYCC;
        } else if (image->numcomps <= 2) {
            image->color_space = OPJ_CLRSPC_GRAY;
        }

        if (image->color_space == OPJ_CLRSPC_SYCC) {
            color_sycc_to_rgb(image);
        } else if ((image->color_space == OPJ_CLRSPC_CMYK) &&
                   (parameters.cod_format != TIF_DFMT)) {
            color_cmyk_to_rgb(image);
        } else if (image->color_space == OPJ_CLRSPC_EYCC) {
            color_esycc_to_rgb(image);
        }

        if (image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
            if (image->icc_profile_len) {
                color_apply_icc_profile(image);
            } else {
                color_cielab_to_rgb(image);
            }
#endif
            free(image->icc_profile_buf);
            image->icc_profile_buf = NULL;
            image->icc_profile_len = 0;
        }

        /* Force output precision */
        /* ---------------------- */
        if (parameters.precision != NULL) {
            OPJ_UINT32 compno;
            for (compno = 0; compno < image->numcomps; ++compno) {
                OPJ_UINT32 precno = compno;
                OPJ_UINT32 prec;

                if (precno >= parameters.nb_precision) {
                    precno = parameters.nb_precision - 1U;
                }

                prec = parameters.precision[precno].prec;
                if (prec == 0) {
                    prec = image->comps[compno].prec;
                }

                switch (parameters.precision[precno].mode) {
                case OPJ_PREC_MODE_CLIP:
                    clip_component(&(image->comps[compno]), prec);
                    break;
                case OPJ_PREC_MODE_SCALE:
                    scale_component(&(image->comps[compno]), prec);
                    break;
                default:
                    break;
                }

            }
        }

        /* Upsample components */
        /* ------------------- */
        if (parameters.upsample) {
            image = upsample_image_components(image);
            if (image == NULL) {
                fprintf(stderr,
                        "ERROR -> opj_decompress: failed to upsample image components!\n");
                opj_destroy_codec(l_codec);
                failed = 1;
                goto fin;
            }
        }

        /* Force RGB output */
        /* ---------------- */
        if (parameters.force_rgb) {
            switch (image->color_space) {
            case OPJ_CLRSPC_SRGB:
                break;
            case OPJ_CLRSPC_GRAY:
                image = convert_gray_to_rgb(image);
                break;
            default:
                fprintf(stderr,
                        "ERROR -> opj_decompress: don't know how to convert image to RGB colorspace!\n");
                opj_image_destroy(image);
                image = NULL;
                break;
            }
            if (image == NULL) {
                fprintf(stderr, "ERROR -> opj_decompress: failed to convert to RGB image!\n");
                opj_destroy_codec(l_codec);
                failed = 1;
                goto fin;
            }
        }

        /* create output image */
        /* ------------------- */
        switch (parameters.cod_format) {
        case PXM_DFMT:          /* PNM PGM PPM */
            if (imagetopnm(image, parameters.outfile, parameters.split_pnm)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case PGX_DFMT:          /* PGX */
            if (imagetopgx(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case BMP_DFMT:          /* BMP */
            if (imagetobmp(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#ifdef OPJ_HAVE_LIBTIFF
        case TIF_DFMT:          /* TIF(F) */
            if (imagetotif(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#endif /* OPJ_HAVE_LIBTIFF */
        case RAW_DFMT:          /* RAW */
            if (imagetoraw(image, parameters.outfile)) {
                fprintf(stderr,
                        "[ERROR] Error generating raw or yuv file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case RAWL_DFMT:         /* RAWL */
            if (imagetorawl(image, parameters.outfile)) {
                fprintf(stderr,
                        "[ERROR] Error generating rawl file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;

        case TGA_DFMT:          /* TGA */
            if (imagetotga(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Error generating tga file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#ifdef OPJ_HAVE_LIBPNG
        case PNG_DFMT:          /* PNG */
            if (imagetopng(image, parameters.outfile)) {
                fprintf(stderr, "[ERROR] Error generating png file. Outfile %s not generated\n",
                        parameters.outfile);
                failed = 1;
            } else if (!(parameters.quiet)) {
                fprintf(stdout, "[INFO] Generated Outfile %s\n", parameters.outfile);
            }
            break;
#endif /* OPJ_HAVE_LIBPNG */
        /* Can happen if output file is TIF(F) or PNG
         * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
        */
        default:
            fprintf(stderr, "[ERROR] Outfile %s not generated\n", parameters.outfile);
            failed = 1;
        }

        /* free remaining structures */
        if (l_codec) {
            opj_destroy_codec(l_codec);
        }

        /* free image data structure */
        opj_image_destroy(image);

        /* destroy the codestream index */
        opj_destroy_cstr_index(&cstr_index);

        if (failed) {
            (void)remove(parameters.outfile);    /* ignore return value */
        }
    }
fin:
    destroy_parameters(&parameters);
    if (failed && img_fol.imgdirpath) {
        free(img_fol.imgdirpath);
    }
    if (dirptr) {
        if (dirptr->filename) {
            free(dirptr->filename);
        }
        if (dirptr->filename_buf) {
            free(dirptr->filename_buf);
        }
        free(dirptr);
    }
    if (numDecompressedImages && !failed && !(parameters.quiet)) {
        fprintf(stdout, "decode time: %d ms\n",
                (int)((tCumulative * 1000.0) / (OPJ_FLOAT64)numDecompressedImages));
    }
    return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}


static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  char
    filename[MaxTextExtent];

  FILE
    *file;

  Image
    *image,
    *next_image,
    *pwp_image;

  ImageInfo
    *read_info;

  int
    c,
    unique_file;

  MagickBooleanType
    status;

  register Image
    *p;

  register ssize_t
    i;

  size_t
    filesize,
    length;

  ssize_t
    count;

  unsigned char
    magick[MaxTextExtent];

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImage(image);
      return((Image *) NULL);
    }
  pwp_image=image;
  memset(magick,0,sizeof(magick));
  count=ReadBlob(pwp_image,5,magick);
  if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  read_info=CloneImageInfo(image_info);
  (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
    (void *) NULL);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  unique_file=AcquireUniqueFileResource(filename);
  (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s",
    filename);
  for ( ; ; )
  {
    (void) memset(magick,0,sizeof(magick));
    for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))
    {
      for (i=0; i < 17; i++)
        magick[i]=magick[i+1];
      magick[17]=(unsigned char) c;
      if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0)
        break;
    }
    if (c == EOF)
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
      }
    if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0)
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowReaderException(CorruptImageError,"ImproperImageHeader");
      }
    /*
      Dump SFW image to a temporary file.
    */
    file=(FILE *) NULL;
    if (unique_file != -1)
      file=fdopen(unique_file,"wb");
    if ((unique_file == -1) || (file == (FILE *) NULL))
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowFileException(exception,FileOpenError,"UnableToWriteFile",
          image->filename);
        image=DestroyImageList(image);
        return((Image *) NULL);
      }
    length=fwrite("SFW94A",1,6,file);
    (void) length;
    filesize=65535UL*magick[2]+256L*magick[1]+magick[0];
    for (i=0; i < (ssize_t) filesize; i++)
    {
      c=ReadBlobByte(pwp_image);
      if (c == EOF)
        break;
      (void) fputc(c,file);
    }
    (void) fclose(file);
    if (c == EOF)
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
      }
    next_image=ReadImage(read_info,exception);
    if (next_image == (Image *) NULL)
      break;
    (void) FormatLocaleString(next_image->filename,MaxTextExtent,
      "slide_%02ld.sfw",(long) next_image->scene);
    if (image == (Image *) NULL)
      image=next_image;
    else
      {
        /*
          Link image into image list.
        */
        for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;
        next_image->previous=p;
        next_image->scene=p->scene+1;
        p->next=next_image;
      }
    if (image_info->number_scenes != 0)
      if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),
      GetBlobSize(pwp_image));
    if (status == MagickFalse)
      break;
  }
  if (unique_file != -1)
    (void) close(unique_file);
  (void) RelinquishUniqueFileResource(filename);
  read_info=DestroyImageInfo(read_info);
  if (image != (Image *) NULL)
    {
      if (EOFBlob(image) != MagickFalse)
        {
          char
            *message;

          message=GetExceptionMessage(errno);
          (void) ThrowMagickException(exception,GetMagickModule(),
            CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename,
            message);
          message=DestroyString(message);
        }
      (void) CloseBlob(image);
    }
  return(GetFirstImageInList(image));
}

The functions ReadDCMImage in coders/dcm.c, ReadPWPImage in coders/pwp.c, ReadCALSImage in coders/cals.c, and ReadPICTImage in coders/pict.c in ImageMagick 7.0.8-4 do not check the return value of the fputc function, which allows remote attackers to cause a denial of service via a crafted image file.


static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  char
    filename[MaxTextExtent];

  FILE
    *file;

  Image
    *image,
    *next_image,
    *pwp_image;

  ImageInfo
    *read_info;

  int
    c,
    unique_file;

  MagickBooleanType
    status;

  register Image
    *p;

  register ssize_t
    i;

  size_t
    filesize,
    length;

  ssize_t
    count;

  unsigned char
    magick[MaxTextExtent];

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImage(image);
      return((Image *) NULL);
    }
  pwp_image=image;
  memset(magick,0,sizeof(magick));
  count=ReadBlob(pwp_image,5,magick);
  if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  read_info=CloneImageInfo(image_info);
  (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
    (void *) NULL);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  unique_file=AcquireUniqueFileResource(filename);
  (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s",
    filename);
  for ( ; ; )
  {
    (void) memset(magick,0,sizeof(magick));
    for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))
    {
      for (i=0; i < 17; i++)
        magick[i]=magick[i+1];
      magick[17]=(unsigned char) c;
      if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0)
        break;
    }
    if (c == EOF)
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
      }
    if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0)
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowReaderException(CorruptImageError,"ImproperImageHeader");
      }
    /*
      Dump SFW image to a temporary file.
    */
    file=(FILE *) NULL;
    if (unique_file != -1)
      file=fdopen(unique_file,"wb");
    if ((unique_file == -1) || (file == (FILE *) NULL))
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowFileException(exception,FileOpenError,"UnableToWriteFile",
          image->filename);
        image=DestroyImageList(image);
        return((Image *) NULL);
      }
    length=fwrite("SFW94A",1,6,file);
    (void) length;
    filesize=65535UL*magick[2]+256L*magick[1]+magick[0];
    for (i=0; i < (ssize_t) filesize; i++)
    {
      c=ReadBlobByte(pwp_image);
      if (c == EOF)
        break;
      if (fputc(c,file) != c)
        break;
    }
    (void) fclose(file);
    if (c == EOF)
      {
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
      }
    next_image=ReadImage(read_info,exception);
    if (next_image == (Image *) NULL)
      break;
    (void) FormatLocaleString(next_image->filename,MaxTextExtent,
      "slide_%02ld.sfw",(long) next_image->scene);
    if (image == (Image *) NULL)
      image=next_image;
    else
      {
        /*
          Link image into image list.
        */
        for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;
        next_image->previous=p;
        next_image->scene=p->scene+1;
        p->next=next_image;
      }
    if (image_info->number_scenes != 0)
      if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),
      GetBlobSize(pwp_image));
    if (status == MagickFalse)
      break;
  }
  if (unique_file != -1)
    (void) close(unique_file);
  (void) RelinquishUniqueFileResource(filename);
  read_info=DestroyImageInfo(read_info);
  if (image != (Image *) NULL)
    {
      if (EOFBlob(image) != MagickFalse)
        {
          char
            *message;

          message=GetExceptionMessage(errno);
          (void) ThrowMagickException(exception,GetMagickModule(),
            CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename,
            message);
          message=DestroyString(message);
        }
      (void) CloseBlob(image);
    }
  return(GetFirstImageInList(image));
}


static Image *ReadCALSImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  char
    filename[MaxTextExtent],
    header[129],
    message[MaxTextExtent];

  FILE
    *file;

  Image
    *image;

  ImageInfo
    *read_info;

  int
    c,
    unique_file;

  MagickBooleanType
    status;

  register ssize_t
    i;

  unsigned long
    density,
    direction,
    height,
    orientation,
    pel_path,
    type,
    width;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read CALS header.
  */
  (void) memset(header,0,sizeof(header));
  density=0;
  direction=0;
  orientation=1;
  pel_path=0;
  type=1;
  width=0;
  height=0;
  for (i=0; i < 16; i++)
  {
    if (ReadBlob(image,128,(unsigned char *) header) != 128)
      break;
    switch (*header)
    {
      case 'R':
      case 'r':
      {
        if (LocaleNCompare(header,"rdensty:",8) == 0)
          {
            (void) sscanf(header+8,"%lu",&density);
            break;
          }
        if (LocaleNCompare(header,"rpelcnt:",8) == 0)
          {
            (void) sscanf(header+8,"%lu,%lu",&width,&height);
            break;
          }
        if (LocaleNCompare(header,"rorient:",8) == 0)
          {
            (void) sscanf(header+8,"%lu,%lu",&pel_path,&direction);
            if (pel_path == 90)
              orientation=5;
            else
              if (pel_path == 180)
                orientation=3;
              else
                if (pel_path == 270)
                  orientation=7;
            if (direction == 90)
              orientation++;
            break;
          }
        if (LocaleNCompare(header,"rtype:",6) == 0)
          {
            (void) sscanf(header+6,"%lu",&type);
            break;
          }
        break;
      }
    }
  }
  /*
    Read CALS pixels.
  */
  file=(FILE *) NULL;
  unique_file=AcquireUniqueFileResource(filename);
  if (unique_file != -1)
    file=fdopen(unique_file,"wb");
  if ((unique_file == -1) || (file == (FILE *) NULL))
    ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
  while ((c=ReadBlobByte(image)) != EOF)
    (void) fputc(c,file);
  (void) fclose(file);
  (void) CloseBlob(image);
  image=DestroyImage(image);
  read_info=CloneImageInfo(image_info);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  (void) FormatLocaleString(read_info->filename,MaxTextExtent,"group4:%s",
    filename);
  (void) FormatLocaleString(message,MaxTextExtent,"%lux%lu",width,height);
  read_info->size=ConstantString(message);
  (void) FormatLocaleString(message,MaxTextExtent,"%lu",density);
  read_info->density=ConstantString(message);
  read_info->orientation=(OrientationType) orientation;
  image=ReadImage(read_info,exception);
  if (image != (Image *) NULL)
    {
      (void) CopyMagickString(image->filename,image_info->filename,
        MaxTextExtent);
      (void) CopyMagickString(image->magick_filename,image_info->filename,
        MaxTextExtent);
      (void) CopyMagickString(image->magick,"CALS",MaxTextExtent);
    }
  read_info=DestroyImageInfo(read_info);
  (void) RelinquishUniqueFileResource(filename);
  return(image);
}


static Image *ReadCALSImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  char
    filename[MaxTextExtent],
    header[129],
    message[MaxTextExtent];

  FILE
    *file;

  Image
    *image;

  ImageInfo
    *read_info;

  int
    c,
    unique_file;

  MagickBooleanType
    status;

  register ssize_t
    i;

  unsigned long
    density,
    direction,
    height,
    orientation,
    pel_path,
    type,
    width;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read CALS header.
  */
  (void) memset(header,0,sizeof(header));
  density=0;
  direction=0;
  orientation=1;
  pel_path=0;
  type=1;
  width=0;
  height=0;
  for (i=0; i < 16; i++)
  {
    if (ReadBlob(image,128,(unsigned char *) header) != 128)
      break;
    switch (*header)
    {
      case 'R':
      case 'r':
      {
        if (LocaleNCompare(header,"rdensty:",8) == 0)
          {
            (void) sscanf(header+8,"%lu",&density);
            break;
          }
        if (LocaleNCompare(header,"rpelcnt:",8) == 0)
          {
            (void) sscanf(header+8,"%lu,%lu",&width,&height);
            break;
          }
        if (LocaleNCompare(header,"rorient:",8) == 0)
          {
            (void) sscanf(header+8,"%lu,%lu",&pel_path,&direction);
            if (pel_path == 90)
              orientation=5;
            else
              if (pel_path == 180)
                orientation=3;
              else
                if (pel_path == 270)
                  orientation=7;
            if (direction == 90)
              orientation++;
            break;
          }
        if (LocaleNCompare(header,"rtype:",6) == 0)
          {
            (void) sscanf(header+6,"%lu",&type);
            break;
          }
        break;
      }
    }
  }
  /*
    Read CALS pixels.
  */
  file=(FILE *) NULL;
  unique_file=AcquireUniqueFileResource(filename);
  if (unique_file != -1)
    file=fdopen(unique_file,"wb");
  if ((unique_file == -1) || (file == (FILE *) NULL))
    ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
  while ((c=ReadBlobByte(image)) != EOF)
    if (fputc(c,file) != c)
      break;
  (void) fclose(file);
  (void) CloseBlob(image);
  image=DestroyImage(image);
  read_info=CloneImageInfo(image_info);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  (void) FormatLocaleString(read_info->filename,MaxTextExtent,"group4:%s",
    filename);
  (void) FormatLocaleString(message,MaxTextExtent,"%lux%lu",width,height);
  read_info->size=ConstantString(message);
  (void) FormatLocaleString(message,MaxTextExtent,"%lu",density);
  read_info->density=ConstantString(message);
  read_info->orientation=(OrientationType) orientation;
  image=ReadImage(read_info,exception);
  if (image != (Image *) NULL)
    {
      (void) CopyMagickString(image->filename,image_info->filename,
        MaxTextExtent);
      (void) CopyMagickString(image->magick_filename,image_info->filename,
        MaxTextExtent);
      (void) CopyMagickString(image->magick,"CALS",MaxTextExtent);
    }
  read_info=DestroyImageInfo(read_info);
  (void) RelinquishUniqueFileResource(filename);
  return(image);
}


static Image *ReadPICTImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
#define ThrowPICTException(exception,message) \
{ \
  if (tile_image != (Image *) NULL) \
    tile_image=DestroyImage(tile_image); \
  if (read_info != (ImageInfo *) NULL) \
    read_info=DestroyImageInfo(read_info); \
  ThrowReaderException((exception),(message)); \
}

  char
    geometry[MaxTextExtent],
    header_ole[4];

  Image
    *image,
    *tile_image;

  ImageInfo
    *read_info;

  IndexPacket
    index;

  int
    c,
    code;

  MagickBooleanType
    jpeg,
    status;

  PICTRectangle
    frame;

  PICTPixmap
    pixmap;

  register IndexPacket
    *indexes;

  register ssize_t
    x;

  register PixelPacket
    *q;

  register ssize_t
    i;

  size_t
    extent,
    length;

  ssize_t
    count,
    flags,
    j,
    version,
    y;

  StringInfo
    *profile;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read PICT header.
  */
  read_info=(ImageInfo *) NULL;
  tile_image=(Image *) NULL;
  pixmap.bits_per_pixel=0;
  pixmap.component_count=0;
  /*
    Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2
  */
  header_ole[0]=ReadBlobByte(image);
  header_ole[1]=ReadBlobByte(image);
  header_ole[2]=ReadBlobByte(image);
  header_ole[3]=ReadBlobByte(image);
  if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
      (header_ole[2] == 0x43) && (header_ole[3] == 0x54)))
    for (i=0; i < 508; i++)
      if (ReadBlobByte(image) == EOF)
        break;
  (void) ReadBlobMSBShort(image);  /* skip picture size */
  if (ReadRectangle(image,&frame) == MagickFalse)
    ThrowPICTException(CorruptImageError,"ImproperImageHeader");
  while ((c=ReadBlobByte(image)) == 0) ;
  if (c != 0x11)
    ThrowPICTException(CorruptImageError,"ImproperImageHeader");
  version=(ssize_t) ReadBlobByte(image);
  if (version == 2)
    {
      c=ReadBlobByte(image);
      if (c != 0xff)
        ThrowPICTException(CorruptImageError,"ImproperImageHeader");
    }
  else
    if (version != 1)
      ThrowPICTException(CorruptImageError,"ImproperImageHeader");
  if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
      (frame.bottom < 0) || (frame.left >= frame.right) ||
      (frame.top >= frame.bottom))
    ThrowPICTException(CorruptImageError,"ImproperImageHeader");
  /*
    Create black canvas.
  */
  flags=0;
  image->depth=8;
  image->columns=(unsigned int) (frame.right-frame.left);
  image->rows=(unsigned int) (frame.bottom-frame.top);
  image->x_resolution=DefaultResolution;
  image->y_resolution=DefaultResolution;
  image->units=UndefinedResolution;
  if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
    if (image->scene >= (image_info->scene+image_info->number_scenes-1))
      {
        (void) CloseBlob(image);
        return(GetFirstImageInList(image));
      }
  status=SetImageExtent(image,image->columns,image->rows);
  if (status != MagickFalse)
    status=ResetImagePixels(image,exception);
  if (status == MagickFalse)
    {
      InheritException(exception,&image->exception);
      return(DestroyImageList(image));
    }
  /*
    Interpret PICT opcodes.
  */
  jpeg=MagickFalse;
  for (code=0; EOFBlob(image) == MagickFalse; )
  {
    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    if ((version == 1) || ((TellBlob(image) % 2) != 0))
      code=ReadBlobByte(image);
    if (version == 2)
      code=ReadBlobMSBSignedShort(image);
    if (code < 0)
      break;
    if (code == 0)
      continue;
    if (code > 0xa1)
      {
        if (image->debug != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
      }
    else
      {
        if (image->debug != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
            "  %04X %s: %s",code,codes[code].name,codes[code].description);
        switch (code)
        {
          case 0x01:
          {
            /*
              Clipping rectangle.
            */
            length=ReadBlobMSBShort(image);
            if (length != 0x000a)
              {
                for (i=0; i < (ssize_t) (length-2); i++)
                  if (ReadBlobByte(image) == EOF)
                    break;
                break;
              }
            if (ReadRectangle(image,&frame) == MagickFalse)
              ThrowPICTException(CorruptImageError,"ImproperImageHeader");
            if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
              break;
            image->columns=(size_t) (frame.right-frame.left);
            image->rows=(size_t) (frame.bottom-frame.top);
            status=SetImageExtent(image,image->columns,image->rows);
            if (status != MagickFalse)
              status=ResetImagePixels(image,&image->exception);
            if (status == MagickFalse)
              {
                InheritException(exception,&image->exception);
                return(DestroyImageList(image));
              }
            break;
          }
          case 0x12:
          case 0x13:
          case 0x14:
          {
            ssize_t
              pattern;

            size_t
              height,
              width;

            /*
              Skip pattern definition.
            */
            pattern=(ssize_t) ReadBlobMSBShort(image);
            for (i=0; i < 8; i++)
              if (ReadBlobByte(image) == EOF)
                break;
            if (pattern == 2)
              {
                for (i=0; i < 5; i++)
                  if (ReadBlobByte(image) == EOF)
                    break;
                break;
              }
            if (pattern != 1)
              ThrowPICTException(CorruptImageError,"UnknownPatternType");
            length=ReadBlobMSBShort(image);
            if (ReadRectangle(image,&frame) == MagickFalse)
              ThrowPICTException(CorruptImageError,"ImproperImageHeader");
            if (ReadPixmap(image,&pixmap) == MagickFalse)
              ThrowPICTException(CorruptImageError,"ImproperImageHeader");
            image->depth=(size_t) pixmap.component_size;
            image->x_resolution=1.0*pixmap.horizontal_resolution;
            image->y_resolution=1.0*pixmap.vertical_resolution;
            image->units=PixelsPerInchResolution;
            (void) ReadBlobMSBLong(image);
            flags=(ssize_t) ReadBlobMSBShort(image);
            length=ReadBlobMSBShort(image);
            for (i=0; i <= (ssize_t) length; i++)
              (void) ReadBlobMSBLong(image);
            width=(size_t) (frame.bottom-frame.top);
            height=(size_t) (frame.right-frame.left);
            if (pixmap.bits_per_pixel <= 8)
              length&=0x7fff;
            if (pixmap.bits_per_pixel == 16)
              width<<=1;
            if (length == 0)
              length=width;
            if (length < 8)
              {
                for (i=0; i < (ssize_t) (length*height); i++)
                  if (ReadBlobByte(image) == EOF)
                    break;
              }
            else
              for (i=0; i < (ssize_t) height; i++)
              {
                if (EOFBlob(image) != MagickFalse)
                  break;
                if (length > 200)
                  {
                    for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
                      if (ReadBlobByte(image) == EOF)
                        break;
                  }
                else
                  for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
                    if (ReadBlobByte(image) == EOF)
                      break;
              }
            break;
          }
          case 0x1b:
          {
            /*
              Initialize image background color.
            */
            image->background_color.red=(Quantum)
              ScaleShortToQuantum(ReadBlobMSBShort(image));
            image->background_color.green=(Quantum)
              ScaleShortToQuantum(ReadBlobMSBShort(image));
            image->background_color.blue=(Quantum)
              ScaleShortToQuantum(ReadBlobMSBShort(image));
            break;
          }
          case 0x70:
          case 0x71:
          case 0x72:
          case 0x73:
          case 0x74:
          case 0x75:
          case 0x76:
          case 0x77:
          {
            /*
              Skip polygon or region.
            */
            length=ReadBlobMSBShort(image);
            for (i=0; i < (ssize_t) (length-2); i++)
              if (ReadBlobByte(image) == EOF)
                break;
            break;
          }
          case 0x90:
          case 0x91:
          case 0x98:
          case 0x99:
          case 0x9a:
          case 0x9b:
          {
            ssize_t
              bytes_per_line;

            PICTRectangle
              source,
              destination;

            register unsigned char
              *p;

            size_t
              j;

            unsigned char
              *pixels;

            /*
              Pixmap clipped by a rectangle.
            */
            bytes_per_line=0;
            if ((code != 0x9a) && (code != 0x9b))
              bytes_per_line=(ssize_t) ReadBlobMSBShort(image);
            else
              {
                (void) ReadBlobMSBShort(image);
                (void) ReadBlobMSBShort(image);
                (void) ReadBlobMSBShort(image);
              }
            if (ReadRectangle(image,&frame) == MagickFalse)
              ThrowPICTException(CorruptImageError,"ImproperImageHeader");
            /*
              Initialize tile image.
            */
            tile_image=CloneImage(image,(size_t) (frame.right-frame.left),
              (size_t) (frame.bottom-frame.top),MagickTrue,exception);
            if (tile_image == (Image *) NULL)
              ThrowPICTException(CorruptImageError,"ImproperImageHeader");
            if ((code == 0x9a) || (code == 0x9b) ||
                ((bytes_per_line & 0x8000) != 0))
              {
                if (ReadPixmap(image,&pixmap) == MagickFalse)
                  ThrowPICTException(CorruptImageError,"ImproperImageHeader");
                tile_image->depth=(size_t) pixmap.component_size;
                tile_image->matte=pixmap.component_count == 4 ?
                  MagickTrue : MagickFalse;
                tile_image->x_resolution=(double) pixmap.horizontal_resolution;
                tile_image->y_resolution=(double) pixmap.vertical_resolution;
                tile_image->units=PixelsPerInchResolution;
                if (tile_image->matte != MagickFalse)
                  (void) SetImageAlphaChannel(tile_image,OpaqueAlphaChannel);
              }
            if ((code != 0x9a) && (code != 0x9b))
              {
                /*
                  Initialize colormap.
                */
                tile_image->colors=2;
                if ((bytes_per_line & 0x8000) != 0)
                  {
                    (void) ReadBlobMSBLong(image);
                    flags=(ssize_t) ReadBlobMSBShort(image);
                    tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
                  }
                status=AcquireImageColormap(tile_image,tile_image->colors);
                if (status == MagickFalse)
                  ThrowPICTException(ResourceLimitError,
                    "MemoryAllocationFailed");
                if ((bytes_per_line & 0x8000) != 0)
                  {
                    for (i=0; i < (ssize_t) tile_image->colors; i++)
                    {
                      j=ReadBlobMSBShort(image) % tile_image->colors;
                      if ((flags & 0x8000) != 0)
                        j=(size_t) i;
                      tile_image->colormap[j].red=(Quantum)
                        ScaleShortToQuantum(ReadBlobMSBShort(image));
                      tile_image->colormap[j].green=(Quantum)
                        ScaleShortToQuantum(ReadBlobMSBShort(image));
                      tile_image->colormap[j].blue=(Quantum)
                        ScaleShortToQuantum(ReadBlobMSBShort(image));
                    }
                  }
                else
                  {
                    for (i=0; i < (ssize_t) tile_image->colors; i++)
                    {
                      tile_image->colormap[i].red=(Quantum) (QuantumRange-
                        tile_image->colormap[i].red);
                      tile_image->colormap[i].green=(Quantum) (QuantumRange-
                        tile_image->colormap[i].green);
                      tile_image->colormap[i].blue=(Quantum) (QuantumRange-
                        tile_image->colormap[i].blue);
                    }
                  }
              }
            if (EOFBlob(image) != MagickFalse)
              ThrowPICTException(CorruptImageError,
                "InsufficientImageDataInFile");
            if (ReadRectangle(image,&source) == MagickFalse)
              ThrowPICTException(CorruptImageError,"ImproperImageHeader");
            if (ReadRectangle(image,&destination) == MagickFalse)
              ThrowPICTException(CorruptImageError,"ImproperImageHeader");
            (void) ReadBlobMSBShort(image);
            if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
              {
                /*
                  Skip region.
                */
                length=ReadBlobMSBShort(image);
                for (i=0; i < (ssize_t) (length-2); i++)
                  if (ReadBlobByte(image) == EOF)
                    break;
              }
            if ((code != 0x9a) && (code != 0x9b) &&
                (bytes_per_line & 0x8000) == 0)
              pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,
                &extent);
            else
              pixels=DecodeImage(image,tile_image,(unsigned int) bytes_per_line,
                (unsigned int) pixmap.bits_per_pixel,&extent);
            if (pixels == (unsigned char *) NULL)
              ThrowPICTException(CorruptImageError,"UnableToUncompressImage");
            /*
              Convert PICT tile image to pixel packets.
            */
            p=pixels;
            for (y=0; y < (ssize_t) tile_image->rows; y++)
            {
              if (p > (pixels+extent+image->columns))
                {
                  pixels=(unsigned char *) RelinquishMagickMemory(pixels);
                  ThrowPICTException(CorruptImageError,"NotEnoughPixelData");
                }
              q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
                exception);
              if (q == (PixelPacket *) NULL)
                break;
              indexes=GetAuthenticIndexQueue(tile_image);
              for (x=0; x < (ssize_t) tile_image->columns; x++)
              {
                if (tile_image->storage_class == PseudoClass)
                  {
                    index=ConstrainColormapIndex(tile_image,*p);
                    SetPixelIndex(indexes+x,index);
                    SetPixelRed(q,
                      tile_image->colormap[(ssize_t) index].red);
                    SetPixelGreen(q,
                      tile_image->colormap[(ssize_t) index].green);
                    SetPixelBlue(q,
                      tile_image->colormap[(ssize_t) index].blue);
                  }
                else
                  {
                    if (pixmap.bits_per_pixel == 16)
                      {
                        i=(ssize_t) (*p++);
                        j=(*p);
                        SetPixelRed(q,ScaleCharToQuantum(
                          (unsigned char) ((i & 0x7c) << 1)));
                        SetPixelGreen(q,ScaleCharToQuantum(
                          (unsigned char) (((i & 0x03) << 6) |
                          ((j & 0xe0) >> 2))));
                        SetPixelBlue(q,ScaleCharToQuantum(
                          (unsigned char) ((j & 0x1f) << 3)));
                      }
                    else
                      if (tile_image->matte == MagickFalse)
                        {
                          if (p > (pixels+extent+2*image->columns))
                            ThrowPICTException(CorruptImageError,
                              "NotEnoughPixelData");
                          SetPixelRed(q,ScaleCharToQuantum(*p));
                          SetPixelGreen(q,ScaleCharToQuantum(
                            *(p+tile_image->columns)));
                          SetPixelBlue(q,ScaleCharToQuantum(
                            *(p+2*tile_image->columns)));
                        }
                      else
                        {
                          if (p > (pixels+extent+3*image->columns))
                            ThrowPICTException(CorruptImageError,
                              "NotEnoughPixelData");
                          SetPixelAlpha(q,ScaleCharToQuantum(*p));
                          SetPixelRed(q,ScaleCharToQuantum(
                            *(p+tile_image->columns)));
                          SetPixelGreen(q,ScaleCharToQuantum(
                            *(p+2*tile_image->columns)));
                          SetPixelBlue(q,ScaleCharToQuantum(
                            *(p+3*tile_image->columns)));
                        }
                  }
                p++;
                q++;
              }
              if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
                break;
              if ((tile_image->storage_class == DirectClass) &&
                  (pixmap.bits_per_pixel != 16))
                {
                  p+=(pixmap.component_count-1)*tile_image->columns;
                  if (p < pixels)
                    break;
                }
              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
                tile_image->rows);
              if (status == MagickFalse)
                break;
            }
            pixels=(unsigned char *) RelinquishMagickMemory(pixels);
            if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))
              if ((code == 0x9a) || (code == 0x9b) ||
                  ((bytes_per_line & 0x8000) != 0))
                (void) CompositeImage(image,CopyCompositeOp,tile_image,
                  (ssize_t) destination.left,(ssize_t) destination.top);
            tile_image=DestroyImage(tile_image);
            break;
          }
          case 0xa1:
          {
            unsigned char
              *info;

            size_t
              type;

            /*
              Comment.
            */
            type=ReadBlobMSBShort(image);
            length=ReadBlobMSBShort(image);
            if (length == 0)
              break;
            (void) ReadBlobMSBLong(image);
            length-=MagickMin(length,4);
            if (length == 0)
              break;
            info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
            if (info == (unsigned char *) NULL)
              break;
            count=ReadBlob(image,length,info);
            if (count != (ssize_t) length)
              {
                info=(unsigned char *) RelinquishMagickMemory(info);
                ThrowPICTException(ResourceLimitError,"UnableToReadImageData");
              }
            switch (type)
            {
              case 0xe0:
              {
                profile=BlobToStringInfo((const void *) NULL,length);
                SetStringInfoDatum(profile,info);
                status=SetImageProfile(image,"icc",profile);
                profile=DestroyStringInfo(profile);
                if (status == MagickFalse)
                  {
                    info=(unsigned char *) RelinquishMagickMemory(info);
                    ThrowPICTException(ResourceLimitError,
                      "MemoryAllocationFailed");
                  }
                break;
              }
              case 0x1f2:
              {
                profile=BlobToStringInfo((const void *) NULL,length);
                SetStringInfoDatum(profile,info);
                status=SetImageProfile(image,"iptc",profile);
                if (status == MagickFalse)
                  {
                    info=(unsigned char *) RelinquishMagickMemory(info);
                    ThrowPICTException(ResourceLimitError,
                      "MemoryAllocationFailed");
                  }
                profile=DestroyStringInfo(profile);
                break;
              }
              default:
                break;
            }
            info=(unsigned char *) RelinquishMagickMemory(info);
            break;
          }
          default:
          {
            /*
              Skip to next op code.
            */
            if (codes[code].length == -1)
              (void) ReadBlobMSBShort(image);
            else
              for (i=0; i < (ssize_t) codes[code].length; i++)
                if (ReadBlobByte(image) == EOF)
                  break;
          }
        }
      }
    if (code == 0xc00)
      {
        /*
          Skip header.
        */
        for (i=0; i < 24; i++)
          if (ReadBlobByte(image) == EOF)
            break;
        continue;
      }
    if (((code >= 0xb0) && (code <= 0xcf)) ||
        ((code >= 0x8000) && (code <= 0x80ff)))
      continue;
    if (code == 0x8200)
      {
        char
          filename[MaxTextExtent];

        FILE
          *file;

        int
          unique_file;

        /*
          Embedded JPEG.
        */
        jpeg=MagickTrue;
        read_info=CloneImageInfo(image_info);
        SetImageInfoBlob(read_info,(void *) NULL,0);
        file=(FILE *) NULL;
        unique_file=AcquireUniqueFileResource(filename);
        (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
          filename);
        if (unique_file != -1)
          file=fdopen(unique_file,"wb");
        if ((unique_file == -1) || (file == (FILE *) NULL))
          {
            (void) RelinquishUniqueFileResource(read_info->filename);
            (void) CopyMagickString(image->filename,read_info->filename,
              MaxTextExtent);
            ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile");
          }
        length=ReadBlobMSBLong(image);
        if (length > 154)
          {
            for (i=0; i < 6; i++)
              (void) ReadBlobMSBLong(image);
            if (ReadRectangle(image,&frame) == MagickFalse)
              {
                (void) fclose(file);
                (void) RelinquishUniqueFileResource(read_info->filename);
                ThrowPICTException(CorruptImageError,"ImproperImageHeader");
              }
            for (i=0; i < 122; i++)
              if (ReadBlobByte(image) == EOF)
                break;
            for (i=0; i < (ssize_t) (length-154); i++)
            {
              c=ReadBlobByte(image);
              if (c == EOF)
                break;
              (void) fputc(c,file);
            }
          }
        (void) fclose(file);
        (void) close(unique_file);
        tile_image=ReadImage(read_info,exception);
        (void) RelinquishUniqueFileResource(filename);
        read_info=DestroyImageInfo(read_info);
        if (tile_image == (Image *) NULL)
          continue;
        (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g",
          (double) MagickMax(image->columns,tile_image->columns),
          (double) MagickMax(image->rows,tile_image->rows));
        (void) SetImageExtent(image,
          MagickMax(image->columns,tile_image->columns),
          MagickMax(image->rows,tile_image->rows));
        (void) TransformImageColorspace(image,tile_image->colorspace);
        (void) CompositeImage(image,CopyCompositeOp,tile_image,(ssize_t)
          frame.left,(ssize_t) frame.right);
        image->compression=tile_image->compression;
        tile_image=DestroyImage(tile_image);
        continue;
      }
    if ((code == 0xff) || (code == 0xffff))
      break;
    if (((code >= 0xd0) && (code <= 0xfe)) ||
        ((code >= 0x8100) && (code <= 0xffff)))
      {
        /*
          Skip reserved.
        */
        length=ReadBlobMSBShort(image);
        for (i=0; i < (ssize_t) length; i++)
          if (ReadBlobByte(image) == EOF)
            break;
        continue;
      }
    if ((code >= 0x100) && (code <= 0x7fff))
      {
        /*
          Skip reserved.
        */
        length=(size_t) ((code >> 7) & 0xff);
        for (i=0; i < (ssize_t) length; i++)
          if (ReadBlobByte(image) == EOF)
            break;
        continue;
      }
  }
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}