/* tif.c - Aldus Tagged Image File Format support */
/*
    libzint - the open source barcode library
    Copyright (C) 2016-2026 Robin Stuart <rstuart114@gmail.com>

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
    3. Neither the name of the project nor the names of its contributors
       may be used to endorse or promote products derived from this software
       without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
 */
/* SPDX-License-Identifier: BSD-3-Clause */

#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include "common.h"
#include "filemem.h"
#include "output.h"
#include "tif.h"

/* PhotometricInterpretation */
#define TIF_PMI_WHITEISZERO     0
#define TIF_PMI_BLACKISZERO     1
#define TIF_PMI_RGB             2
#define TIF_PMI_PALETTE_COLOR   3
#define TIF_PMI_SEPARATED       5 /* CMYK */

/* Compression */
#define TIF_NO_COMPRESSION      1
#define TIF_LZW                 5

static void tif_to_color_map(const unsigned char rgb[4], tiff_color_t *color_map_entry) {
    color_map_entry->red = (rgb[0] << 8) | rgb[0];
    color_map_entry->green = (rgb[1] << 8) | rgb[1];
    color_map_entry->blue = (rgb[2] << 8) | rgb[2];
}

static void tif_to_cmyk(const char *colour, unsigned char *cmyk) {
    int cyan, magenta, yellow, black;
    unsigned char alpha;

    (void) zint_out_colour_get_cmyk(colour, &cyan, &magenta, &yellow, &black, &alpha);
    cmyk[0] = (unsigned char) roundf(cyan * 0xFF / 100.0f);
    cmyk[1] = (unsigned char) roundf(magenta * 0xFF / 100.0f);
    cmyk[2] = (unsigned char) roundf(yellow * 0xFF / 100.0f);
    cmyk[3] = (unsigned char) roundf(black * 0xFF / 100.0f);
    cmyk[4] = alpha;
}

/* LZW stuff - see `tif_lzw_compress()` below */

#define TIF_LZW_CLEAR_CODE      256
#define TIF_LZW_EOI_CODE        257 /* EndOfInformation */
#define TIF_LZW_MIN_BITS        9
#define TIF_LZW_MAX_BITS        12
#define TIF_LZW_TABLE_SIZE      4096 /* (1 << TIF_LZW_MAX_BITS) */

/* Write `code` to output `fmp` in 8-bit batches, returning updated `bytes_put` */
static int tif_lzw_putCode(struct filemem *fmp, const int code, const int bitsPerCode, int *p_bits, int bytes_put) {
    int bits = *p_bits & 0x0FFF; /* Actual bits in buffer */
    int num_bits = (*p_bits >> 16) & 0x0FFF; /* No. of bits in buffer */

    bits = (bits << bitsPerCode) | code;

    for (num_bits += bitsPerCode; num_bits >= 8; num_bits -= 8) {
        zint_fm_putc((bits >> (num_bits - 8)) & 0xFF, fmp);
        bytes_put++;
    }

    bits &= (1 << num_bits) - 1;

    *p_bits = (num_bits << 16) | bits;

    return bytes_put;
}

/* LZW compression adapted from TwelveMonkeys ImageIO's `LZWEncoder::encode()`, returns no. of bytes written */
/* Copyright (c) 2015, Harald Kuhr */
/* SPDX-License-Identifier: BSD-3-Clause */
/* Tree algorithm from "LZW Compression Used to Encode/Decode a GIF File", Bob Montgomery, 1988, see
   https://gingko.homeip.net/docs/file_formats/lzwgif.html#bob
   "manuscript in public domain" according to "Encyclopedia of Graphics File Formats" (2nd edition, 1996)
   by James D. Murray and William vanRyper, Chapter 9 "Data Compression", p.178
*/
/* Copyright (C) 1988 Bob Montgomery */
static int tif_lzw_compress(struct filemem *fmp, const unsigned char *bp, const unsigned int blen) {
    short suffixes[TIF_LZW_TABLE_SIZE] = {0}; /* "shade[]" in Montgomery diagram */
    /* A child is made up of a parent (or prefix) code plus a suffix byte
       and siblings are strings with a common parent (or prefix) and different suffix bytes */
    short children[TIF_LZW_TABLE_SIZE] = {0}; /* "child[]" in Montgomery diagram */
    short siblings[TIF_LZW_TABLE_SIZE] = {0}; /* "sib[]" in Montgomery diagram */

    int parent;
    int bitsPerCode = TIF_LZW_MIN_BITS; /* "codesize" in Montgomery diagram, goes from 9 to 12 */
    int nextValidCode = TIF_LZW_EOI_CODE + 1; /* "nvc" - next available slot in `suffixes` */
    int maxCode = (1 << bitsPerCode) - 1; /* If `nextValidCode` hits this, `bitsPerCode` will have to be adjusted */

    int bits = 0; /* Buffer for partial codes, top 16-bits no. of bits, bottom the bits */
    int bytes_put = 0; /* No. of bytes output */

    const unsigned char *const be = bp + blen;

    assert(blen != 0);

    /* Init */
    bytes_put = tif_lzw_putCode(fmp, TIF_LZW_CLEAR_CODE & maxCode, bitsPerCode, &bits, bytes_put);
    parent = *bp++; /* Parent is 1st code */

    while (bp < be) {
        const int value = *bp++; /* "color" in Montgomery diagram */
        int child = children[parent];

        /* Does parent have a child? */
        if (child) {
            /* Is child right value? */
            if (suffixes[child] == value) {
                parent = child; /* Make new parent */
            } else {
                int sibling = child; /* Makes loop easier */
                /* Try siblings */
                for (;;) {
                    /* Does sibling have a sibling? */
                    if (siblings[sibling]) {
                        sibling = siblings[sibling];
                        /* Is sibling right value? */
                        if (suffixes[sibling] == value) {
                            parent = sibling; /* Make new parent */
                            break;
                        }
                    } else {
                        /* Create one */
                        siblings[sibling] = (short) nextValidCode;
                        goto update_child; /* Hack to avoid having func with large no. of args */
                    }
                }
            }
        /* Parent does not have a child */
        } else {
            /* Create one */
            children[parent] = (short) nextValidCode;
update_child:
            suffixes[nextValidCode] = (short) value;
            bytes_put = tif_lzw_putCode(fmp, parent & maxCode, bitsPerCode, &bits, bytes_put); /* Put the code */
            parent = value;
            if (++nextValidCode > maxCode) {
                /* Adjust `bitsPerCode` (code size) if required */
                if (bitsPerCode == TIF_LZW_MAX_BITS) {
                    /* Signal reset by writing Clear code */
                    bytes_put = tif_lzw_putCode(fmp, TIF_LZW_CLEAR_CODE & maxCode, bitsPerCode, &bits, bytes_put);

                    /* Reset tables */
                    memset(children, 0, sizeof(short) * TIF_LZW_TABLE_SIZE);
                    memset(siblings, 0, sizeof(short) * TIF_LZW_TABLE_SIZE);
                    bitsPerCode = TIF_LZW_MIN_BITS;
                    nextValidCode = TIF_LZW_EOI_CODE + 1;
                } else {
                    /* Increase code size */
                    bitsPerCode++;
                }
                maxCode = (1 << bitsPerCode) - 1;
            }
        }
    }

    /* Write EOI when we are done */
    bytes_put = tif_lzw_putCode(fmp, parent & maxCode, bitsPerCode, &bits, bytes_put);
    bytes_put = tif_lzw_putCode(fmp, TIF_LZW_EOI_CODE & maxCode, bitsPerCode, &bits, bytes_put);

    /* Flush partial codes */
    if (bits) {
        const int num_bits = (bits >> 16) & 0x0FFF;
        zint_fm_putc((bits << (8 - num_bits)) & 0xFF, fmp); /* Zero pad */
        bytes_put++;
    }

    return bytes_put;
}

/* TIFF Revision 6.0 https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFF6.pdf */
INTERNAL int zint_tif_pixel_plot(struct zint_symbol *symbol, const unsigned char *pixelbuf) {
    unsigned char fg[4], bg[4];
    int i;
    int pmi; /* PhotometricInterpretation */
    int rows_per_strip, strip_count;
    int rows_last_strip;
    int bytes_per_strip;
    uint16_t bits_per_sample;
    int samples_per_pixel;
    int pixels_per_sample;
    unsigned char map[256];
    tiff_color_t color_map[256] = {{0}};
    unsigned char palette[256][5];
    int color_map_size = 0;
    int extra_samples = 0;
    size_t free_memory;
    int row, column, strip;
    int strip_row;
    unsigned int bytes_put;
    long total_bytes_put;
    struct filemem fm;
    struct filemem *const fmp = &fm;
    const unsigned char *pb;
    int compression = TIF_NO_COMPRESSION;
    const int output_to_stdout = symbol->output_options & BARCODE_STDOUT;
    uint32_t *strip_offset;
    uint32_t *strip_bytes;
    unsigned char *strip_buf;

    tiff_header_t header;
    uint16_t entries = 0;
    tiff_tag_t tags[20];
    uint32_t offset = 0;
    int update_offsets[20];
    int offsets = 0;
    int ifd_size;
    uint32_t temp32;
    uint16_t temp16;
    int have_alpha;
    const int grayscale = zint_out_grayscale(symbol);

    (void) zint_out_colour_get_rgb(symbol->fgcolour, &fg[0], &fg[1], &fg[2], &fg[3]);
    (void) zint_out_colour_get_rgb(symbol->bgcolour, &bg[0], &bg[1], &bg[2], &bg[3]);

    have_alpha = fg[3] != 0xFF || bg[3] != 0xFF;

    if (symbol->symbology == BARCODE_ULTRA) {
        static const unsigned char ultra_chars[8] = { 'W', 'C', 'B', 'M', 'R', 'Y', 'G', 'K' };

        if (symbol->output_options & CMYK_COLOUR) {
            static const unsigned char ultra_cmyks[8][4] = {
                {    0,    0,    0,    0 }, /* White */
                { 0xFF,    0,    0,    0 }, /* Cyan */
                { 0xFF, 0xFF,    0,    0 }, /* Blue */
                {    0, 0xFF,    0,    0 }, /* Magenta */
                {    0, 0xFF, 0xFF,    0 }, /* Red */
                {    0,    0, 0xFF,    0 }, /* Yellow */
                { 0xFF,    0, 0xFF,    0 }, /* Green */
                {    0,    0,    0, 0xFF }, /* Black */
            };
            for (i = 0; i < 8; i++) {
                map[ultra_chars[i]] = i;
                memcpy(palette[i], ultra_cmyks[i], 4);
                palette[i][4] = fg[3];
            }
            map['0'] = 8;
            tif_to_cmyk(symbol->bgcolour, palette[8]);
            map['1'] = 9;
            tif_to_cmyk(symbol->fgcolour, palette[9]);

            pmi = TIF_PMI_SEPARATED;
            bits_per_sample = 8;
            samples_per_pixel = 4 + have_alpha;
            pixels_per_sample = 1;
            extra_samples = have_alpha; /* Associated alpha */
        } else {
            static const unsigned char ultra_rgbs[8][3] = {
                { 0xff, 0xff, 0xff, }, /* White */
                {    0, 0xff, 0xff, }, /* Cyan */
                {    0,    0, 0xff, }, /* Blue */
                { 0xff,    0, 0xff, }, /* Magenta */
                { 0xff,    0,    0, }, /* Red */
                { 0xff, 0xff,    0, }, /* Yellow */
                {    0, 0xff,    0, }, /* Green */
                {    0,    0,    0, }, /* Black */
            };
            for (i = 0; i < 8; i++) {
                map[ultra_chars[i]] = i;
                memcpy(palette[i], ultra_rgbs[i], 3);
                palette[i][3] = fg[3];
            }
            map['0'] = 8;
            memcpy(palette[8], bg, 4);
            map['1'] = 9;
            memcpy(palette[9], fg, 4);

            if (!have_alpha) {
                pmi = TIF_PMI_PALETTE_COLOR;
                for (i = 0; i < 10; i++) {
                    tif_to_color_map(palette[i], &color_map[i]);
                }
                bits_per_sample = 4;
                samples_per_pixel = 1;
                pixels_per_sample = 2;
                color_map_size = 16; /* 2**BitsPerSample */
            } else {
                pmi = TIF_PMI_RGB;
                bits_per_sample = 8;
                samples_per_pixel = 4;
                pixels_per_sample = 1;
                extra_samples = 1; /* Associated alpha */
            }
        }
    } else if (grayscale) { /* Anti-aliased */
        if (symbol->output_options & CMYK_COLOUR) {
            int diff_cyan, diff_magenta, diff_yellow, diff_black, diff_alpha;

            tif_to_cmyk(symbol->bgcolour, palette[0]);
            tif_to_cmyk(symbol->fgcolour, palette[0xFF]);

            diff_cyan = palette[0xFF][0] - palette[0][0];
            diff_magenta = palette[0xFF][1] - palette[0][1];
            diff_yellow = palette[0xFF][2] - palette[0][2];
            diff_black = palette[0xFF][3] - palette[0][3];
            diff_alpha = palette[0xFF][4] - palette[0][4];
            for (i = 1; i < 0xFF; i++) {
                palette[i][0] = palette[0][0] + (diff_cyan * i) / 100.0f;
                palette[i][1] = palette[0][1] + (diff_magenta * i) / 100.0f;
                palette[i][2] = palette[0][2] + (diff_yellow * i) / 100.0f;
                palette[i][3] = palette[0][3] + (diff_black * i) / 100.0f;
                if (have_alpha) {
                    palette[i][4] = palette[0][4] + (diff_alpha * i) / 100.0f;
                }
                map[i] = i;
            }
            pmi = TIF_PMI_SEPARATED;
            bits_per_sample = 8;
            samples_per_pixel = 4 + have_alpha;
            pixels_per_sample = 1;
            extra_samples = have_alpha; /* Associated alpha */
        } else {
            const int diff_red = fg[0] - bg[0];
            const int diff_green = fg[1] - bg[1];
            const int diff_blue = fg[2] - bg[2];
            const int diff_alpha = fg[3] - bg[3];
            for (i = 0; i <= 0xFF; i++) {
                palette[i][0] = bg[0] + (diff_red * i) / 0xFF;
                palette[i][1] = bg[1] + (diff_green * i) / 0xFF;
                palette[i][2] = bg[2] + (diff_blue * i) / 0xFF;
                if (have_alpha) {
                    palette[i][3] = bg[3] + (diff_alpha * i) / 0xFF;
                }
                map[i] = i;
            }
            pmi = TIF_PMI_RGB;
            bits_per_sample = 8;
            samples_per_pixel = 3 + have_alpha;
            pixels_per_sample = 1;
            extra_samples = have_alpha; /* Associated alpha */
        }
    } else { /* fg/bg only */
        if (symbol->output_options & CMYK_COLOUR) {
            map['0'] = 0;
            tif_to_cmyk(symbol->bgcolour, palette[0]);
            map['1'] = 1;
            tif_to_cmyk(symbol->fgcolour, palette[1]);

            pmi = TIF_PMI_SEPARATED;
            bits_per_sample = 8;
            samples_per_pixel = 4 + have_alpha;
            pixels_per_sample = 1;
            extra_samples = have_alpha; /* Associated alpha */
        } else if (bg[0] == 0xff && bg[1] == 0xff && bg[2] == 0xff && bg[3] == 0xff
                    && fg[0] == 0 && fg[1] == 0 && fg[2] == 0 && fg[3] == 0xff) {
            map['0'] = 0;
            map['1'] = 1;

            pmi = TIF_PMI_WHITEISZERO;
            bits_per_sample = 1;
            samples_per_pixel = 1;
            pixels_per_sample = 8;
        } else if (bg[0] == 0 && bg[1] == 0 && bg[2] == 0 && bg[3] == 0xff
                && fg[0] == 0xff && fg[1] == 0xff && fg[2] == 0xff && fg[3] == 0xff) {
            map['0'] = 0;
            map['1'] = 1;

            pmi = TIF_PMI_BLACKISZERO;
            bits_per_sample = 1;
            samples_per_pixel = 1;
            pixels_per_sample = 8;
        } else {
            map['0'] = 0;
            memcpy(palette[0], bg, 4);
            map['1'] = 1;
            memcpy(palette[1], fg, 4);

            pmi = TIF_PMI_PALETTE_COLOR;
            for (i = 0; i < 2; i++) {
                tif_to_color_map(palette[i], &color_map[i]);
            }
            if (!have_alpha) {
                bits_per_sample = 4;
                samples_per_pixel = 1;
                pixels_per_sample = 2;
                color_map_size = 16; /* 2**BitsPerSample */
            } else {
                bits_per_sample = 8;
                samples_per_pixel = 2;
                pixels_per_sample = 1;
                color_map_size = 256; /* 2**BitsPerSample */
                extra_samples = 1; /* Associated alpha */
            }
        }
    }

    /* TIFF Rev 6 Section 7 p.27 "Set RowsPerStrip such that the size of each strip is about 8K bytes...
     * Note that extremely wide high resolution images may have rows larger than 8K bytes; in this case,
     * RowsPerStrip should be 1, and the strip will be larger than 8K." */
    rows_per_strip = (8192 * pixels_per_sample) / (symbol->bitmap_width * samples_per_pixel);
    if (rows_per_strip == 0) {
        rows_per_strip = 1;
    }

    /* Suppresses clang-tidy clang-analyzer-core.VLASize warning */
    assert(symbol->bitmap_height > 0);

    if (rows_per_strip >= symbol->bitmap_height) {
        strip_count = 1;
        rows_per_strip = rows_last_strip = symbol->bitmap_height;
    } else {
        strip_count = symbol->bitmap_height / rows_per_strip;
        rows_last_strip = symbol->bitmap_height % rows_per_strip;
        if (rows_last_strip != 0) {
            strip_count++;
        }
        if (rows_per_strip > symbol->bitmap_height) {
            rows_per_strip = rows_last_strip = symbol->bitmap_height;
        }
    }
    assert(strip_count > 0); /* Suppress clang-analyzer-core.UndefinedBinaryOperatorResult */

    if (symbol->debug & ZINT_DEBUG_PRINT) {
        printf("TIFF (%dx%d) Strip Count %d, Rows Per Strip %d, Pixels Per Sample %d, Samples Per Pixel %d, PMI %d\n",
            symbol->bitmap_width, symbol->bitmap_height, strip_count, rows_per_strip, pixels_per_sample,
            samples_per_pixel, pmi);
    }

    bytes_per_strip = rows_per_strip * ((symbol->bitmap_width + pixels_per_sample - 1) / pixels_per_sample)
                        * samples_per_pixel;
    assert(bytes_per_strip >= 0); /* Suppress clang-tidy-21 clang-analyzer-security.ArrayBound */

    strip_offset = (uint32_t *) z_alloca(sizeof(uint32_t) * strip_count);
    strip_bytes = (uint32_t *) z_alloca(sizeof(uint32_t) * strip_count);
    strip_buf = (unsigned char *) z_alloca(bytes_per_strip + 1);

    free_memory = sizeof(tiff_header_t);

    for (i = 0; i < strip_count; i++) {
        strip_offset[i] = (uint32_t) free_memory;
        if (i != (strip_count - 1)) {
            strip_bytes[i] = bytes_per_strip;
        } else {
            if (rows_last_strip) {
                strip_bytes[i] = rows_last_strip
                                    * ((symbol->bitmap_width + pixels_per_sample - 1) / pixels_per_sample)
                                    * samples_per_pixel;
            } else {
                strip_bytes[i] = bytes_per_strip;
            }
        }
        free_memory += strip_bytes[i];
    }
    if (free_memory & 1) {
        free_memory++; /* IFD must be on word boundary */
    }

    if (free_memory > 0xffff0000) {
        return z_errtxt(ZINT_ERROR_MEMORY, symbol, 670, "TIF output file size too big");
    }

    /* Open output file in binary mode */
    if (!zint_fm_open(fmp, symbol, "wb")) {
        return ZEXT z_errtxtf(ZINT_ERROR_FILE_ACCESS, symbol, 672, "Could not open TIF output file (%1$d: %2$s)",
                                fmp->err, strerror(fmp->err));
    }
    if (!output_to_stdout) {
        compression = TIF_LZW;
    }

    /* Header */
    zint_out_le_u16(header.byte_order, 0x4949); /* "II" little-endian */
    zint_out_le_u16(header.identity, 42);
    zint_out_le_u32(header.offset, free_memory);

    zint_fm_write(&header, sizeof(tiff_header_t), 1, fmp);
    total_bytes_put = sizeof(tiff_header_t);

    /* Pixel data */
    pb = pixelbuf;
    strip = 0;
    strip_row = 0;
    bytes_put = 0;
    for (row = 0; row < symbol->bitmap_height; row++) {
        if (samples_per_pixel == 1) {
            if (bits_per_sample == 1) { /* WHITEISZERO or BLACKISZERO */
                for (column = 0; column < symbol->bitmap_width; column += 8) {
                    unsigned char byte = 0;
                    for (i = 0; i < 8 && column + i < symbol->bitmap_width; i++, pb++) {
                        byte |= map[*pb] << (7 - i);
                    }
                    strip_buf[bytes_put++] = byte;
                }
            } else { /* bits_per_sample == 4, PALETTE_COLOR with no alpha */
                for (column = 0; column < symbol->bitmap_width; column += 2) {
                    unsigned char byte = map[*pb++] << 4;
                    if (column + 1 < symbol->bitmap_width) {
                        byte |= map[*pb++];
                    }
                    strip_buf[bytes_put++] = byte;
                }
            }
        } else if (samples_per_pixel == 2) { /* PALETTE_COLOR with alpha */
            for (column = 0; column < symbol->bitmap_width; column++) {
                const int idx = map[*pb++];
                strip_buf[bytes_put++] = idx;
                strip_buf[bytes_put++] = palette[idx][3];
            }
        } else { /* samples_per_pixel >= 4, RGB with alpha (4) or CMYK with (5) or without (4) alpha */
            for (column = 0; column < symbol->bitmap_width; column++) {
                const int idx = map[*pb++];
                memcpy(&strip_buf[bytes_put], &palette[idx], samples_per_pixel);
                bytes_put += samples_per_pixel;
            }
        }

        strip_row++;

        if (strip_row == rows_per_strip || (strip == strip_count - 1 && strip_row == rows_last_strip)) {
            /* End of strip */
            if (compression == TIF_LZW) {
                #ifndef NDEBUG
                long before_file_pos, after_file_pos;
                if ((before_file_pos = zint_fm_tell(fmp)) == -1L) {
                    (void) zint_fm_close(fmp, symbol);
                    return z_errtxt(ZINT_ERROR_FILE_WRITE, symbol, 671, "Failed to get file position in TIF output");
                }
                #endif

                bytes_put = tif_lzw_compress(fmp, strip_buf, bytes_put);

                #ifndef NDEBUG
                if ((after_file_pos = zint_fm_tell(fmp)) == -1L) {
                    (void) zint_fm_close(fmp, symbol);
                    return z_errtxt(ZINT_ERROR_FILE_WRITE, symbol, 673, "Failed to get file position in TIF output");
                }
                assert(bytes_put == (unsigned int) (after_file_pos - before_file_pos));
                #endif

                if (bytes_put != strip_bytes[strip]) {
                    const int diff = bytes_put - strip_bytes[strip];
                    strip_bytes[strip] = bytes_put;
                    for (i = strip + 1; i < strip_count; i++) {
                        strip_offset[i] += diff;
                    }
                }
            } else {
                zint_fm_write(strip_buf, 1, bytes_put, fmp);
            }
            strip++;
            total_bytes_put += bytes_put;
            bytes_put = 0;
            strip_row = 0;
            /* Suppress clang-analyzer-core.UndefinedBinaryOperatorResult */
            assert(strip < strip_count || row + 1 == symbol->bitmap_height);
        }
    }

    if (total_bytes_put & 1) {
        zint_fm_putc(0, fmp); /* IFD must be on word boundary */
        total_bytes_put++;
    }

    if (compression == TIF_LZW) {
        long file_pos;
        if ((file_pos = zint_fm_tell(fmp)) == -1L) {
            (void) zint_fm_close(fmp, symbol);
            return z_errtxt(ZINT_ERROR_FILE_WRITE, symbol, 675, "Failed to get file position in TIF output");
        }
        zint_fm_seek(fmp, 4, SEEK_SET);
        free_memory = file_pos;
        temp32 = (uint32_t) free_memory;
        /* Shouldn't happen as `free_memory` checked above to be <= 0xffff0000 & should only decrease */
        if (free_memory != temp32 || (long) free_memory != file_pos) {
            (void) zint_fm_close(fmp, symbol);
            return z_errtxt(ZINT_ERROR_MEMORY, symbol, 982, "TIF output file size too big");
        }
        zint_out_le_u32(temp32, temp32);
        zint_fm_write(&temp32, 4, 1, fmp);
        zint_fm_seek(fmp, file_pos, SEEK_SET);
    }

    /* Image File Directory */
    zint_out_le_u16(tags[entries].tag, 0x0100); /* ImageWidth */
    zint_out_le_u16(tags[entries].type, 3); /* SHORT */
    zint_out_le_u32(tags[entries].count, 1);
    zint_out_le_u32(tags[entries++].offset, symbol->bitmap_width);

    zint_out_le_u16(tags[entries].tag, 0x0101); /* ImageLength - number of rows */
    zint_out_le_u16(tags[entries].type, 3); /* SHORT */
    zint_out_le_u32(tags[entries].count, 1);
    zint_out_le_u32(tags[entries++].offset, symbol->bitmap_height);

    if (samples_per_pixel != 1 || bits_per_sample != 1) {
        zint_out_le_u16(tags[entries].tag, 0x0102); /* BitsPerSample */
        zint_out_le_u16(tags[entries].type, 3); /* SHORT */
        zint_out_le_u32(tags[entries].count, samples_per_pixel);
        if (samples_per_pixel == 1) {
            zint_out_le_u32(tags[entries++].offset, bits_per_sample);
        } else if (samples_per_pixel == 2) { /* 2 SHORTS fit into LONG offset so packed into offset */
            zint_out_le_u32(tags[entries++].offset, (bits_per_sample << 16) | bits_per_sample);
        } else {
            update_offsets[offsets++] = entries;
            tags[entries++].offset = (uint32_t) free_memory;
            free_memory += samples_per_pixel * 2;
        }
    }

    zint_out_le_u16(tags[entries].tag, 0x0103); /* Compression */
    zint_out_le_u16(tags[entries].type, 3); /* SHORT */
    zint_out_le_u32(tags[entries].count, 1);
    zint_out_le_u32(tags[entries++].offset, compression);

    zint_out_le_u16(tags[entries].tag, 0x0106); /* PhotometricInterpretation */
    zint_out_le_u16(tags[entries].type, 3); /* SHORT */
    zint_out_le_u32(tags[entries].count, 1);
    zint_out_le_u32(tags[entries++].offset, pmi);

    zint_out_le_u16(tags[entries].tag, 0x0111); /* StripOffsets */
    zint_out_le_u16(tags[entries].type, 4); /* LONG */
    zint_out_le_u32(tags[entries].count, strip_count);
    if (strip_count == 1) {
        zint_out_le_u32(tags[entries++].offset, strip_offset[0]);
    } else {
        update_offsets[offsets++] = entries;
        tags[entries++].offset = (uint32_t) free_memory;
        free_memory += strip_count * 4;
    }

    if (samples_per_pixel > 1) {
        zint_out_le_u16(tags[entries].tag, 0x0115); /* SamplesPerPixel */
        zint_out_le_u16(tags[entries].type, 3); /* SHORT */
        zint_out_le_u32(tags[entries].count, 1);
        zint_out_le_u32(tags[entries++].offset, samples_per_pixel);
    }

    zint_out_le_u16(tags[entries].tag, 0x0116); /* RowsPerStrip */
    zint_out_le_u16(tags[entries].type, 4); /* LONG */
    zint_out_le_u32(tags[entries].count, 1);
    zint_out_le_u32(tags[entries++].offset, rows_per_strip);

    zint_out_le_u16(tags[entries].tag, 0x0117); /* StripByteCounts */
    zint_out_le_u16(tags[entries].type, 4); /* LONG */
    zint_out_le_u32(tags[entries].count, strip_count);
    if (strip_count == 1) {
        zint_out_le_u32(tags[entries++].offset, strip_bytes[0]);
    } else {
        update_offsets[offsets++] = entries;
        tags[entries++].offset = (uint32_t) free_memory;
        free_memory += strip_count * 4;
    }

    zint_out_le_u16(tags[entries].tag, 0x011a); /* XResolution */
    zint_out_le_u16(tags[entries].type, 5); /* RATIONAL */
    zint_out_le_u32(tags[entries].count, 1);
    update_offsets[offsets++] = entries;
    tags[entries++].offset = (uint32_t) free_memory;
    free_memory += 8;

    zint_out_le_u16(tags[entries].tag, 0x011b); /* YResolution */
    zint_out_le_u16(tags[entries].type, 5); /* RATIONAL */
    zint_out_le_u32(tags[entries].count, 1);
    update_offsets[offsets++] = entries;
    tags[entries++].offset = (uint32_t) free_memory;
    free_memory += 8;

    zint_out_le_u16(tags[entries].tag, 0x0128); /* ResolutionUnit */
    zint_out_le_u16(tags[entries].type, 3); /* SHORT */
    zint_out_le_u32(tags[entries].count, 1);
    if (symbol->dpmm) {
        zint_out_le_u32(tags[entries++].offset, 3); /* Centimetres */
    } else {
        zint_out_le_u32(tags[entries++].offset, 2); /* Inches */
    }

    if (color_map_size) {
        zint_out_le_u16(tags[entries].tag, 0x0140); /* ColorMap */
        zint_out_le_u16(tags[entries].type, 3); /* SHORT */
        zint_out_le_u32(tags[entries].count, color_map_size * 3);
        update_offsets[offsets++] = entries;
        tags[entries++].offset = (uint32_t) free_memory;
        /* free_memory += color_map_size * 3 * 2; Unnecessary as long as last use */
    }

    if (extra_samples) {
        zint_out_le_u16(tags[entries].tag, 0x0152); /* ExtraSamples */
        zint_out_le_u16(tags[entries].type, 3); /* SHORT */
        zint_out_le_u32(tags[entries].count, 1);
        zint_out_le_u32(tags[entries++].offset, extra_samples);
    }

    ifd_size = sizeof(entries) + sizeof(tiff_tag_t) * entries + sizeof(offset);
    for (i = 0; i < offsets; i++) {
        zint_out_le_u32(tags[update_offsets[i]].offset, tags[update_offsets[i]].offset + ifd_size);
    }

    zint_out_le_u16(temp16, entries);
    zint_fm_write(&temp16, sizeof(entries), 1, fmp);
    zint_fm_write(&tags, sizeof(tiff_tag_t), entries, fmp);
    zint_out_le_u32(offset, offset);
    zint_fm_write(&offset, sizeof(offset), 1, fmp);
    total_bytes_put += ifd_size;

    if (samples_per_pixel > 2) {
        zint_out_le_u16(bits_per_sample, bits_per_sample);
        for (i = 0; i < samples_per_pixel; i++) {
            zint_fm_write(&bits_per_sample, sizeof(bits_per_sample), 1, fmp);
        }
        total_bytes_put += sizeof(bits_per_sample) * samples_per_pixel;
    }

    if (strip_count != 1) {
        /* Strip offsets */
        for (i = 0; i < strip_count; i++) {
            zint_out_le_u32(temp32, strip_offset[i]);
            zint_fm_write(&temp32, 4, 1, fmp);
        }

        /* Strip byte lengths */
        for (i = 0; i < strip_count; i++) {
            zint_out_le_u32(temp32, strip_bytes[i]);
            zint_fm_write(&temp32, 4, 1, fmp);
        }
        total_bytes_put += strip_count * 8;
    }

    /* XResolution */
    zint_out_le_u32(temp32, symbol->dpmm ? symbol->dpmm : 72);
    zint_fm_write(&temp32, 4, 1, fmp);
    zint_out_le_u32(temp32, symbol->dpmm ? 10 /*cm*/ : 1);
    zint_fm_write(&temp32, 4, 1, fmp);
    total_bytes_put += 8;

    /* YResolution */
    zint_out_le_u32(temp32, symbol->dpmm ? symbol->dpmm : 72);
    zint_fm_write(&temp32, 4, 1, fmp);
    zint_out_le_u32(temp32, symbol->dpmm ? 10 /*cm*/ : 1);
    zint_fm_write(&temp32, 4, 1, fmp);
    total_bytes_put += 8;

    if (color_map_size) {
        for (i = 0; i < color_map_size; i++) {
            zint_fm_write(&color_map[i].red, 2, 1, fmp);
        }
        for (i = 0; i < color_map_size; i++) {
            zint_fm_write(&color_map[i].green, 2, 1, fmp);
        }
        for (i = 0; i < color_map_size; i++) {
            zint_fm_write(&color_map[i].blue, 2, 1, fmp);
        }
        total_bytes_put += 6 * color_map_size;
    }

    if (zint_fm_error(fmp)) {
        ZEXT z_errtxtf(0, symbol, 679, "Incomplete write of TIF output (%1$d: %2$s)", fmp->err, strerror(fmp->err));
        (void) zint_fm_close(fmp, symbol);
        return ZINT_ERROR_FILE_WRITE;
    }

    if (!output_to_stdout) {
        if (zint_fm_tell(fmp) != total_bytes_put) {
            (void) zint_fm_close(fmp, symbol);
            return z_errtxt(ZINT_ERROR_FILE_WRITE, symbol, 674, "Failed to write all TIF output");
        }
    }
    if (!zint_fm_close(fmp, symbol)) {
        return ZEXT z_errtxtf(ZINT_ERROR_FILE_WRITE, symbol, 981, "Failure on closing TIF output file (%1$d: %2$s)",
                                fmp->err, strerror(fmp->err));
    }

    return 0;
}

/* vim: set ts=4 sw=4 et : */
