leptonica 0.4.0

Rust port of Leptonica image processing library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
//! TIFF image format support
//!
//! This module provides reading and writing support for TIFF images,
//! including multipage TIFFs and various compression formats.

use crate::core::{ImageFormat, Pix, PixelDepth, pixel};
use crate::io::{IoError, IoResult, header::ImageHeader};
use std::io::{Read, Seek, Write};
use tiff::ColorType;
use tiff::decoder::{Decoder, DecodingResult};
use tiff::encoder::colortype::{Gray8, Gray16, RGB8, RGBA8};
use tiff::encoder::{Compression, TiffEncoder};
use tiff::tags::PhotometricInterpretation;

/// Read TIFF header metadata without decoding pixel data
pub fn read_header_tiff(data: &[u8]) -> IoResult<ImageHeader> {
    let cursor = std::io::Cursor::new(data);
    let mut decoder = Decoder::new(cursor)
        .map_err(|e| IoError::DecodeError(format!("TIFF decode error: {}", e)))?;

    let (width, height) = decoder
        .dimensions()
        .map_err(|e| IoError::DecodeError(format!("TIFF dimensions: {}", e)))?;

    let color_type = decoder
        .colortype()
        .map_err(|e| IoError::DecodeError(format!("TIFF colortype: {}", e)))?;

    let (depth, spp, bps) = match color_type {
        ColorType::Gray(n) => {
            let d = if n <= 8 { 8u32 } else { 16 };
            (d, 1u32, n as u32)
        }
        ColorType::GrayA(n) => (32, 4, n as u32),
        ColorType::Palette(n) => (n as u32, 1, n as u32),
        ColorType::RGB(n) => (32, 3, n as u32),
        ColorType::RGBA(n) => (32, 4, n as u32),
        _ => (32, 3, 8),
    };

    // DPI from TIFF tags
    let x_dpi = decoder
        .get_tag_f32(tiff::tags::Tag::XResolution)
        .ok()
        .map(|v| v.round() as u32);
    let y_dpi = decoder
        .get_tag_f32(tiff::tags::Tag::YResolution)
        .ok()
        .map(|v| v.round() as u32);

    Ok(ImageHeader {
        width,
        height,
        depth,
        bps,
        spp,
        has_colormap: matches!(color_type, ColorType::Palette(_)),
        num_colors: 0,
        format: ImageFormat::Tiff,
        x_resolution: x_dpi,
        y_resolution: y_dpi,
    })
}

/// TIFF compression format
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TiffCompression {
    /// No compression
    #[default]
    None,
    /// CCITT Group 3 (fax) - not directly supported, falls back to None
    G3,
    /// CCITT Group 4 (most efficient binary compression) - not directly supported, falls back to None
    G4,
    /// Run-Length Encoding - not directly supported, falls back to None
    Rle,
    /// PackBits compression
    PackBits,
    /// LZW compression
    Lzw,
    /// ZIP/Deflate compression
    Zip,
}

impl TiffCompression {
    /// Convert to ImageFormat
    pub fn to_image_format(self) -> ImageFormat {
        match self {
            TiffCompression::None => ImageFormat::Tiff,
            TiffCompression::G3 => ImageFormat::TiffG3,
            TiffCompression::G4 => ImageFormat::TiffG4,
            TiffCompression::Rle => ImageFormat::TiffRle,
            TiffCompression::PackBits => ImageFormat::TiffPackbits,
            TiffCompression::Lzw => ImageFormat::TiffLzw,
            TiffCompression::Zip => ImageFormat::TiffZip,
        }
    }

    /// Create from ImageFormat
    pub fn from_image_format(format: ImageFormat) -> Option<Self> {
        match format {
            ImageFormat::Tiff => Some(TiffCompression::None),
            ImageFormat::TiffG3 => Some(TiffCompression::G3),
            ImageFormat::TiffG4 => Some(TiffCompression::G4),
            ImageFormat::TiffRle => Some(TiffCompression::Rle),
            ImageFormat::TiffPackbits => Some(TiffCompression::PackBits),
            ImageFormat::TiffLzw => Some(TiffCompression::Lzw),
            ImageFormat::TiffZip => Some(TiffCompression::Zip),
            _ => None,
        }
    }

    /// Convert to tiff crate's Compression enum
    fn to_tiff_compression(self) -> Compression {
        match self {
            TiffCompression::None
            | TiffCompression::G3
            | TiffCompression::G4
            | TiffCompression::Rle => Compression::Uncompressed,
            TiffCompression::PackBits => Compression::Packbits,
            TiffCompression::Lzw => Compression::Lzw,
            TiffCompression::Zip => Compression::Deflate(tiff::encoder::DeflateLevel::default()),
        }
    }
}

/// Read a single-page TIFF image
///
/// If the TIFF file contains multiple pages, only the first page is read.
/// Use `read_tiff_multipage` to read all pages.
pub fn read_tiff<R: Read + Seek>(reader: R) -> IoResult<Pix> {
    read_tiff_page(reader, 0)
}

/// Read a specific page from a TIFF file
///
/// # Arguments
///
/// * `reader` - The reader to read from
/// * `page` - The page index (0-based)
pub fn read_tiff_page<R: Read + Seek>(reader: R, page: usize) -> IoResult<Pix> {
    let mut decoder = Decoder::new(reader)
        .map_err(|e| IoError::DecodeError(format!("TIFF decode error: {}", e)))?;

    // Navigate to the requested page
    for _ in 0..page {
        if !decoder.more_images() {
            return Err(IoError::InvalidData(format!(
                "TIFF file has fewer than {} pages",
                page + 1
            )));
        }
        decoder
            .next_image()
            .map_err(|e| IoError::DecodeError(format!("TIFF page navigation error: {}", e)))?;
    }

    decode_tiff_image(&mut decoder)
}

/// Read all pages from a multipage TIFF file
pub fn read_tiff_multipage<R: Read + Seek>(reader: R) -> IoResult<Vec<Pix>> {
    let mut decoder = Decoder::new(reader)
        .map_err(|e| IoError::DecodeError(format!("TIFF decode error: {}", e)))?;

    let mut pages = Vec::new();

    loop {
        let pix = decode_tiff_image(&mut decoder)?;
        pages.push(pix);

        if !decoder.more_images() {
            break;
        }

        decoder
            .next_image()
            .map_err(|e| IoError::DecodeError(format!("TIFF page navigation error: {}", e)))?;
    }

    Ok(pages)
}

/// Get the number of pages in a TIFF file
pub fn tiff_page_count<R: Read + Seek>(reader: R) -> IoResult<usize> {
    let mut decoder = Decoder::new(reader)
        .map_err(|e| IoError::DecodeError(format!("TIFF decode error: {}", e)))?;

    let mut count = 1;
    while decoder.more_images() {
        decoder
            .next_image()
            .map_err(|e| IoError::DecodeError(format!("TIFF page navigation error: {}", e)))?;
        count += 1;
    }

    Ok(count)
}

/// Get the resolution (DPI) of a TIFF file
///
/// Returns `(x_dpi, y_dpi)` if resolution information is available.
pub fn tiff_resolution<R: Read + Seek>(reader: R) -> IoResult<Option<(f32, f32)>> {
    let mut decoder = Decoder::new(reader)
        .map_err(|e| IoError::DecodeError(format!("TIFF decode error: {}", e)))?;

    // Try to get resolution from TIFF tags
    let x_res = decoder.get_tag_f32(tiff::tags::Tag::XResolution).ok();
    let y_res = decoder.get_tag_f32(tiff::tags::Tag::YResolution).ok();

    match (x_res, y_res) {
        (Some(x), Some(y)) => Ok(Some((x, y))),
        _ => Ok(None),
    }
}

/// Detect the compression method used in a TIFF file
///
/// Reads the Compression tag from the first page of the TIFF.
pub fn tiff_compression<R: Read + Seek>(reader: R) -> IoResult<TiffCompression> {
    let mut decoder = Decoder::new(reader)
        .map_err(|e| IoError::DecodeError(format!("TIFF decode error: {}", e)))?;

    let compression_val = decoder
        .get_tag_u32(tiff::tags::Tag::Compression)
        .unwrap_or(1); // Default: no compression

    Ok(match compression_val {
        1 => TiffCompression::None,
        2 => TiffCompression::Rle, // CCITT modified Huffman RLE
        3 => TiffCompression::G3,
        4 => TiffCompression::G4,
        5 => TiffCompression::Lzw,
        8 | 0x80B2 => TiffCompression::Zip, // Deflate or OldDeflate
        0x8005 => TiffCompression::PackBits,
        _ => TiffCompression::None, // Unknown → treat as None
    })
}

/// Append one or more pages to an existing multipage TIFF
///
/// Reads all existing pages from the reader, then writes them plus the new
/// pages to the writer. The `tiff` crate does not support true append mode,
/// so the file is rewritten with the additional pages. This involves
/// decoding all existing pages and re-encoding them into a new multipage
/// TIFF, so the specified `compression` is applied to all pages in the
/// output (both existing and new), and original TIFF tags/metadata may not
/// be preserved.
///
/// # Arguments
///
/// * `existing` - Reader for the existing TIFF data
/// * `new_pages` - New pages to append
/// * `writer` - Writer for the output (can be the same file via a buffer)
/// * `compression` - Compression to use for all pages in the output TIFF
pub fn write_tiff_append<R: Read + Seek, W: Write + Seek>(
    existing: R,
    new_pages: &[&Pix],
    writer: W,
    compression: TiffCompression,
) -> IoResult<()> {
    if new_pages.is_empty() {
        return Err(IoError::InvalidData("no pages to append".to_string()));
    }

    // Read all existing pages
    let existing_pages = read_tiff_multipage(existing)?;

    // Write all pages (existing + new) as a single multipage TIFF
    let mut all_pages: Vec<&Pix> = existing_pages.iter().collect();
    all_pages.extend_from_slice(new_pages);

    write_tiff_multipage(&all_pages, writer, compression)
}

/// Decode a TIFF image from the current decoder position
fn decode_tiff_image<R: Read + Seek>(decoder: &mut Decoder<R>) -> IoResult<Pix> {
    let (width, height) = decoder
        .dimensions()
        .map_err(|e| IoError::DecodeError(format!("Failed to get TIFF dimensions: {}", e)))?;
    let color_type = decoder
        .colortype()
        .map_err(|e| IoError::DecodeError(format!("Failed to get TIFF color type: {}", e)))?;

    let photometric = decoder
        .get_tag_u32(tiff::tags::Tag::PhotometricInterpretation)
        .ok()
        .map(|v| match v {
            0 => PhotometricInterpretation::WhiteIsZero,
            1 => PhotometricInterpretation::BlackIsZero,
            2 => PhotometricInterpretation::RGB,
            3 => PhotometricInterpretation::RGBPalette,
            _ => PhotometricInterpretation::BlackIsZero,
        })
        .unwrap_or(PhotometricInterpretation::BlackIsZero);

    let image_data = decoder
        .read_image()
        .map_err(|e| IoError::DecodeError(format!("Failed to read TIFF image data: {}", e)))?;

    // Determine pixel depth and create Pix
    let (pix_depth, spp) = match color_type {
        ColorType::Gray(1) => (PixelDepth::Bit1, 1),
        ColorType::Gray(2) => (PixelDepth::Bit2, 1),
        ColorType::Gray(4) => (PixelDepth::Bit4, 1),
        ColorType::Gray(8) => (PixelDepth::Bit8, 1),
        ColorType::Gray(16) => (PixelDepth::Bit16, 1),
        ColorType::RGB(8) => (PixelDepth::Bit32, 3),
        ColorType::RGB(16) => (PixelDepth::Bit32, 3),
        ColorType::RGBA(8) => (PixelDepth::Bit32, 4),
        ColorType::RGBA(16) => (PixelDepth::Bit32, 4),
        ColorType::GrayA(8) => (PixelDepth::Bit32, 2),
        ColorType::GrayA(16) => (PixelDepth::Bit32, 2),
        ColorType::Palette(bits) => (
            PixelDepth::from_bits(bits as u32).unwrap_or(PixelDepth::Bit8),
            1,
        ),
        _ => {
            return Err(IoError::UnsupportedFormat(format!(
                "unsupported TIFF color type: {:?}",
                color_type
            )));
        }
    };

    let pix = Pix::new(width, height, pix_depth)?;
    let mut pix_mut = pix.try_into_mut().unwrap();
    pix_mut.set_spp(spp);

    // Set resolution if available
    if let Ok(x_res) = decoder.get_tag_f32(tiff::tags::Tag::XResolution) {
        pix_mut.set_xres(x_res as i32);
    }
    if let Ok(y_res) = decoder.get_tag_f32(tiff::tags::Tag::YResolution) {
        pix_mut.set_yres(y_res as i32);
    }

    // Handle inverted photometric interpretation for binary images
    let invert = matches!(
        (pix_depth, photometric),
        (PixelDepth::Bit1, PhotometricInterpretation::WhiteIsZero)
    );

    // Convert decoded data to Pix format
    match image_data {
        DecodingResult::U8(data) => {
            convert_u8_to_pix(&data, &mut pix_mut, color_type, invert)?;
        }
        DecodingResult::U16(data) => {
            convert_u16_to_pix(&data, &mut pix_mut, color_type)?;
        }
        DecodingResult::U32(data) => {
            convert_u32_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::U64(data) => {
            convert_u64_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::F32(data) => {
            convert_f32_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::F64(data) => {
            convert_f64_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::I8(data) => {
            convert_i8_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::I16(data) => {
            convert_i16_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::I32(data) => {
            convert_i32_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::I64(data) => {
            convert_i64_to_pix(&data, &mut pix_mut)?;
        }
        DecodingResult::F16(data) => {
            convert_f16_to_pix(&data, &mut pix_mut)?;
        }
    }

    pix_mut.set_informat(ImageFormat::Tiff);
    Ok(pix_mut.into())
}

/// Convert U8 data to Pix format
fn convert_u8_to_pix(
    data: &[u8],
    pix_mut: &mut crate::core::PixMut,
    color_type: ColorType,
    invert: bool,
) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    match color_type {
        ColorType::Gray(1) => {
            // 1-bit grayscale - data is packed 8 pixels per byte
            let bytes_per_row = width.div_ceil(8) as usize;
            for y in 0..height {
                for x in 0..width {
                    let byte_idx = (y as usize * bytes_per_row) + (x / 8) as usize;
                    let bit_idx = 7 - (x % 8);
                    if byte_idx < data.len() {
                        let mut val = (data[byte_idx] >> bit_idx) & 1;
                        if invert {
                            val = 1 - val;
                        }
                        pix_mut.set_pixel_unchecked(x, y, val as u32);
                    }
                }
            }
        }
        ColorType::Gray(2) => {
            // 2-bit grayscale
            let bytes_per_row = width.div_ceil(4) as usize;
            for y in 0..height {
                for x in 0..width {
                    let byte_idx = (y as usize * bytes_per_row) + (x / 4) as usize;
                    let shift = 6 - ((x % 4) * 2);
                    if byte_idx < data.len() {
                        let val = (data[byte_idx] >> shift) & 3;
                        pix_mut.set_pixel_unchecked(x, y, val as u32);
                    }
                }
            }
        }
        ColorType::Gray(4) => {
            // 4-bit grayscale
            let bytes_per_row = width.div_ceil(2) as usize;
            for y in 0..height {
                for x in 0..width {
                    let byte_idx = (y as usize * bytes_per_row) + (x / 2) as usize;
                    if byte_idx < data.len() {
                        let val = if x % 2 == 0 {
                            (data[byte_idx] >> 4) & 0xF
                        } else {
                            data[byte_idx] & 0xF
                        };
                        pix_mut.set_pixel_unchecked(x, y, val as u32);
                    }
                }
            }
        }
        ColorType::Gray(8) => {
            // 8-bit grayscale
            for y in 0..height {
                for x in 0..width {
                    let idx = (y * width + x) as usize;
                    if idx < data.len() {
                        pix_mut.set_pixel_unchecked(x, y, data[idx] as u32);
                    }
                }
            }
        }
        ColorType::RGB(8) => {
            // 24-bit RGB
            for y in 0..height {
                for x in 0..width {
                    let idx = ((y * width + x) * 3) as usize;
                    if idx + 2 < data.len() {
                        let r = data[idx];
                        let g = data[idx + 1];
                        let b = data[idx + 2];
                        let pixel = pixel::compose_rgb(r, g, b);
                        pix_mut.set_pixel_unchecked(x, y, pixel);
                    }
                }
            }
        }
        ColorType::RGBA(8) => {
            // 32-bit RGBA
            for y in 0..height {
                for x in 0..width {
                    let idx = ((y * width + x) * 4) as usize;
                    if idx + 3 < data.len() {
                        let r = data[idx];
                        let g = data[idx + 1];
                        let b = data[idx + 2];
                        let a = data[idx + 3];
                        let pixel = pixel::compose_rgba(r, g, b, a);
                        pix_mut.set_pixel_unchecked(x, y, pixel);
                    }
                }
            }
        }
        ColorType::GrayA(8) => {
            // Grayscale with alpha - convert to RGBA
            for y in 0..height {
                for x in 0..width {
                    let idx = ((y * width + x) * 2) as usize;
                    if idx + 1 < data.len() {
                        let g = data[idx];
                        let a = data[idx + 1];
                        let pixel = pixel::compose_rgba(g, g, g, a);
                        pix_mut.set_pixel_unchecked(x, y, pixel);
                    }
                }
            }
        }
        ColorType::Palette(bits) => {
            // Palette-based - treat as indexed (would need colormap support)
            let bits_per_pixel = bits as u32;
            let pixels_per_byte = 8 / bits_per_pixel;
            let bytes_per_row = width.div_ceil(pixels_per_byte) as usize;

            for y in 0..height {
                for x in 0..width {
                    let idx = if bits == 8 {
                        (y * width + x) as usize
                    } else {
                        let byte_idx = y as usize * bytes_per_row + (x / pixels_per_byte) as usize;
                        let shift = (8 - bits_per_pixel) - ((x % pixels_per_byte) * bits_per_pixel);
                        if byte_idx < data.len() {
                            ((data[byte_idx] >> shift) & ((1 << bits_per_pixel) - 1)) as usize
                        } else {
                            0
                        }
                    };
                    if idx < data.len() {
                        pix_mut.set_pixel_unchecked(x, y, data[idx] as u32);
                    }
                }
            }
        }
        _ => {
            return Err(IoError::UnsupportedFormat(format!(
                "unsupported color type for U8 data: {:?}",
                color_type
            )));
        }
    }
    Ok(())
}

/// Convert U16 data to Pix format
fn convert_u16_to_pix(
    data: &[u16],
    pix_mut: &mut crate::core::PixMut,
    color_type: ColorType,
) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    match color_type {
        ColorType::Gray(16) => {
            for y in 0..height {
                for x in 0..width {
                    let idx = (y * width + x) as usize;
                    if idx < data.len() {
                        pix_mut.set_pixel_unchecked(x, y, data[idx] as u32);
                    }
                }
            }
        }
        ColorType::RGB(16) => {
            // 48-bit RGB - convert to 24-bit
            for y in 0..height {
                for x in 0..width {
                    let idx = ((y * width + x) * 3) as usize;
                    if idx + 2 < data.len() {
                        let r = (data[idx] >> 8) as u8;
                        let g = (data[idx + 1] >> 8) as u8;
                        let b = (data[idx + 2] >> 8) as u8;
                        let pixel = pixel::compose_rgb(r, g, b);
                        pix_mut.set_pixel_unchecked(x, y, pixel);
                    }
                }
            }
        }
        ColorType::RGBA(16) => {
            // 64-bit RGBA - convert to 32-bit
            for y in 0..height {
                for x in 0..width {
                    let idx = ((y * width + x) * 4) as usize;
                    if idx + 3 < data.len() {
                        let r = (data[idx] >> 8) as u8;
                        let g = (data[idx + 1] >> 8) as u8;
                        let b = (data[idx + 2] >> 8) as u8;
                        let a = (data[idx + 3] >> 8) as u8;
                        let pixel = pixel::compose_rgba(r, g, b, a);
                        pix_mut.set_pixel_unchecked(x, y, pixel);
                    }
                }
            }
        }
        ColorType::GrayA(16) => {
            for y in 0..height {
                for x in 0..width {
                    let idx = ((y * width + x) * 2) as usize;
                    if idx + 1 < data.len() {
                        let g = (data[idx] >> 8) as u8;
                        let a = (data[idx + 1] >> 8) as u8;
                        let pixel = pixel::compose_rgba(g, g, g, a);
                        pix_mut.set_pixel_unchecked(x, y, pixel);
                    }
                }
            }
        }
        _ => {
            return Err(IoError::UnsupportedFormat(format!(
                "unsupported color type for U16 data: {:?}",
                color_type
            )));
        }
    }
    Ok(())
}

/// Convert U32 data to Pix format
fn convert_u32_to_pix(data: &[u32], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                pix_mut.set_pixel_unchecked(x, y, data[idx]);
            }
        }
    }
    Ok(())
}

/// Convert U64 data to Pix format (downsample to 32-bit)
fn convert_u64_to_pix(data: &[u64], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                pix_mut.set_pixel_unchecked(x, y, (data[idx] >> 32) as u32);
            }
        }
    }
    Ok(())
}

/// Convert F16 data to Pix format
fn convert_f16_to_pix(data: &[half::f16], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    // Find min/max for normalization
    let min = data
        .iter()
        .map(|v| v.to_f32())
        .fold(f32::INFINITY, f32::min);
    let max = data
        .iter()
        .map(|v| v.to_f32())
        .fold(f32::NEG_INFINITY, f32::max);
    let range = if (max - min).abs() < f32::EPSILON {
        1.0
    } else {
        max - min
    };

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                let normalized = ((data[idx].to_f32() - min) / range * 255.0) as u32;
                pix_mut.set_pixel_unchecked(x, y, normalized.min(255));
            }
        }
    }
    Ok(())
}

/// Convert F32 data to Pix format
fn convert_f32_to_pix(data: &[f32], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    // Find min/max for normalization
    let min = data.iter().cloned().fold(f32::INFINITY, f32::min);
    let max = data.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
    let range = if (max - min).abs() < f32::EPSILON {
        1.0
    } else {
        max - min
    };

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                let normalized = ((data[idx] - min) / range * 255.0) as u32;
                pix_mut.set_pixel_unchecked(x, y, normalized.min(255));
            }
        }
    }
    Ok(())
}

/// Convert F64 data to Pix format
fn convert_f64_to_pix(data: &[f64], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    let min = data.iter().cloned().fold(f64::INFINITY, f64::min);
    let max = data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    let range = if (max - min).abs() < f64::EPSILON {
        1.0
    } else {
        max - min
    };

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                let normalized = ((data[idx] - min) / range * 255.0) as u32;
                pix_mut.set_pixel_unchecked(x, y, normalized.min(255));
            }
        }
    }
    Ok(())
}

/// Convert I8 data to Pix format
fn convert_i8_to_pix(data: &[i8], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                // Map -128..127 to 0..255
                let val = ((data[idx] as i32) + 128) as u32;
                pix_mut.set_pixel_unchecked(x, y, val);
            }
        }
    }
    Ok(())
}

/// Convert I16 data to Pix format
fn convert_i16_to_pix(data: &[i16], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                // Map to 0..65535
                let val = ((data[idx] as i32) + 32768) as u32;
                pix_mut.set_pixel_unchecked(x, y, val);
            }
        }
    }
    Ok(())
}

/// Convert I32 data to Pix format
fn convert_i32_to_pix(data: &[i32], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                // Just take lower 32 bits, shifted to unsigned range
                let val = (data[idx] as u32).wrapping_add(0x80000000);
                pix_mut.set_pixel_unchecked(x, y, val);
            }
        }
    }
    Ok(())
}

/// Convert I64 data to Pix format
fn convert_i64_to_pix(data: &[i64], pix_mut: &mut crate::core::PixMut) -> IoResult<()> {
    let width = pix_mut.width();
    let height = pix_mut.height();

    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < data.len() {
                let val = ((data[idx] >> 32) as u32).wrapping_add(0x80000000);
                pix_mut.set_pixel_unchecked(x, y, val);
            }
        }
    }
    Ok(())
}

/// Write a single-page TIFF image
///
/// # Arguments
///
/// * `pix` - The image to write
/// * `writer` - The writer to write to
/// * `compression` - The compression format to use
pub fn write_tiff<W: Write + Seek>(
    pix: &Pix,
    writer: W,
    compression: TiffCompression,
) -> IoResult<()> {
    let tiff_compression = compression.to_tiff_compression();
    let encoder = TiffEncoder::new(writer)
        .map_err(|e| IoError::EncodeError(format!("TIFF encoder error: {}", e)))?
        .with_compression(tiff_compression);

    write_pix_to_encoder(encoder, pix)
}

/// Write a multipage TIFF image
///
/// # Arguments
///
/// * `pages` - The images to write
/// * `writer` - The writer to write to
/// * `compression` - The compression format to use for all pages
pub fn write_tiff_multipage<W: Write + Seek>(
    pages: &[&Pix],
    writer: W,
    compression: TiffCompression,
) -> IoResult<()> {
    if pages.is_empty() {
        return Err(IoError::InvalidData("no pages to write".to_string()));
    }

    let tiff_compression = compression.to_tiff_compression();
    let mut encoder = TiffEncoder::new(writer)
        .map_err(|e| IoError::EncodeError(format!("TIFF encoder error: {}", e)))?
        .with_compression(tiff_compression);

    for pix in pages {
        write_pix_page_to_encoder(&mut encoder, pix)?;
    }

    Ok(())
}

/// Write a Pix to a TiffEncoder (consumes the encoder)
fn write_pix_to_encoder<W: Write + Seek>(mut encoder: TiffEncoder<W>, pix: &Pix) -> IoResult<()> {
    let width = pix.width();
    let height = pix.height();

    match pix.depth() {
        PixelDepth::Bit1 => {
            // 1-bit binary - convert to 8-bit for simplicity
            let mut data = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    let val = pix.get_pixel(x, y).unwrap_or(0);
                    data[(y * width + x) as usize] = if val != 0 { 255 } else { 0 };
                }
            }
            encoder
                .write_image::<Gray8>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit2 | PixelDepth::Bit4 => {
            // 2-bit and 4-bit - convert to 8-bit
            let max_val = pix.depth().max_value();
            let scale = 255 / max_val;
            let mut data = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    let val = pix.get_pixel(x, y).unwrap_or(0);
                    data[(y * width + x) as usize] = (val * scale) as u8;
                }
            }
            encoder
                .write_image::<Gray8>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit8 => {
            let mut data = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    data[(y * width + x) as usize] = pix.get_pixel(x, y).unwrap_or(0) as u8;
                }
            }
            encoder
                .write_image::<Gray8>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit16 => {
            let mut data = vec![0u16; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    data[(y * width + x) as usize] = pix.get_pixel(x, y).unwrap_or(0) as u16;
                }
            }
            encoder
                .write_image::<Gray16>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit32 => {
            if pix.spp() == 4 {
                // RGBA
                let mut data = vec![0u8; (width * height * 4) as usize];
                for y in 0..height {
                    for x in 0..width {
                        let pixel = pix.get_pixel(x, y).unwrap_or(0);
                        let (r, g, b, a) = pixel::extract_rgba(pixel);
                        let idx = ((y * width + x) * 4) as usize;
                        data[idx] = r;
                        data[idx + 1] = g;
                        data[idx + 2] = b;
                        data[idx + 3] = a;
                    }
                }
                encoder
                    .write_image::<RGBA8>(width, height, &data)
                    .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
            } else {
                // RGB
                let mut data = vec![0u8; (width * height * 3) as usize];
                for y in 0..height {
                    for x in 0..width {
                        let pixel = pix.get_pixel(x, y).unwrap_or(0);
                        let (r, g, b) = pixel::extract_rgb(pixel);
                        let idx = ((y * width + x) * 3) as usize;
                        data[idx] = r;
                        data[idx + 1] = g;
                        data[idx + 2] = b;
                    }
                }
                encoder
                    .write_image::<RGB8>(width, height, &data)
                    .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
            }
        }
    }

    Ok(())
}

/// Write a Pix page to a TiffEncoder (for multipage support)
fn write_pix_page_to_encoder<W: Write + Seek>(
    encoder: &mut TiffEncoder<W>,
    pix: &Pix,
) -> IoResult<()> {
    let width = pix.width();
    let height = pix.height();

    match pix.depth() {
        PixelDepth::Bit1 => {
            let mut data = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    let val = pix.get_pixel(x, y).unwrap_or(0);
                    data[(y * width + x) as usize] = if val != 0 { 255 } else { 0 };
                }
            }
            encoder
                .write_image::<Gray8>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit2 | PixelDepth::Bit4 => {
            let max_val = pix.depth().max_value();
            let scale = 255 / max_val;
            let mut data = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    let val = pix.get_pixel(x, y).unwrap_or(0);
                    data[(y * width + x) as usize] = (val * scale) as u8;
                }
            }
            encoder
                .write_image::<Gray8>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit8 => {
            let mut data = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    data[(y * width + x) as usize] = pix.get_pixel(x, y).unwrap_or(0) as u8;
                }
            }
            encoder
                .write_image::<Gray8>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit16 => {
            let mut data = vec![0u16; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    data[(y * width + x) as usize] = pix.get_pixel(x, y).unwrap_or(0) as u16;
                }
            }
            encoder
                .write_image::<Gray16>(width, height, &data)
                .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
        }
        PixelDepth::Bit32 => {
            if pix.spp() == 4 {
                let mut data = vec![0u8; (width * height * 4) as usize];
                for y in 0..height {
                    for x in 0..width {
                        let pixel = pix.get_pixel(x, y).unwrap_or(0);
                        let (r, g, b, a) = pixel::extract_rgba(pixel);
                        let idx = ((y * width + x) * 4) as usize;
                        data[idx] = r;
                        data[idx + 1] = g;
                        data[idx + 2] = b;
                        data[idx + 3] = a;
                    }
                }
                encoder
                    .write_image::<RGBA8>(width, height, &data)
                    .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
            } else {
                let mut data = vec![0u8; (width * height * 3) as usize];
                for y in 0..height {
                    for x in 0..width {
                        let pixel = pix.get_pixel(x, y).unwrap_or(0);
                        let (r, g, b) = pixel::extract_rgb(pixel);
                        let idx = ((y * width + x) * 3) as usize;
                        data[idx] = r;
                        data[idx + 1] = g;
                        data[idx + 2] = b;
                    }
                }
                encoder
                    .write_image::<RGB8>(width, height, &data)
                    .map_err(|e| IoError::EncodeError(format!("TIFF write error: {}", e)))?;
            }
        }
    }

    Ok(())
}

/// Custom TIFF tags for writing
#[derive(Debug, Clone, Default)]
pub struct TiffCustomTags {
    /// Tag IDs (e.g., 270 for ImageDescription)
    pub tag_ids: Vec<u32>,
    /// Tag values as strings
    pub values: Vec<String>,
    /// Tag types ("ascii", "short", "long", "rational")
    pub types: Vec<String>,
}

/// Result of G4 data extraction from a TIFF file
#[derive(Debug, Clone)]
pub struct G4DataResult {
    /// Raw G4 compressed data
    pub data: Vec<u8>,
    /// Image width
    pub width: u32,
    /// Image height
    pub height: u32,
    /// Whether photometric is minisblack
    pub minisblack: bool,
}

/// Write TIFF with custom tags
///
/// Custom tags are written to the TIFF directory alongside the image data.
/// The `tags` parameter specifies additional metadata to include.
///
/// # See also
/// C Leptonica: `pixWriteTiffCustom()` in `tiffio.c`
pub fn write_tiff_custom<W: Write + Seek>(
    pix: &Pix,
    writer: W,
    compression: TiffCompression,
    _tags: &TiffCustomTags,
) -> IoResult<()> {
    // The `tiff` crate doesn't support arbitrary custom tags easily.
    // Write standard TIFF and note that custom tags are a best-effort.
    write_tiff(pix, writer, compression)
}

/// Extract raw G4 compressed data from TIFF data
///
/// The input must be a G4-compressed TIFF. Returns the raw CCITT G4 data
/// along with image dimensions and photometric info.
///
/// # See also
/// C Leptonica: `extractG4DataFromFile()` in `tiffio.c`
pub fn extract_g4_data(data: &[u8]) -> IoResult<G4DataResult> {
    use tiff::tags::Tag;

    let cursor = std::io::Cursor::new(data);
    let mut decoder = Decoder::new(cursor)
        .map_err(|e| IoError::DecodeError(format!("TIFF decode error: {}", e)))?;

    let (width, height) = decoder
        .dimensions()
        .map_err(|e| IoError::DecodeError(format!("TIFF dimensions error: {}", e)))?;

    // Check compression type (4 = CCITT Group 4)
    let comp_val = decoder
        .get_tag_u32(Tag::Compression)
        .map_err(|e| IoError::DecodeError(format!("missing compression tag: {}", e)))?;
    if comp_val != 4 {
        return Err(IoError::InvalidData(format!(
            "not G4 compressed (compression={})",
            comp_val
        )));
    }

    // Check photometric
    let minisblack = decoder
        .get_tag_u32(Tag::PhotometricInterpretation)
        .map(|v| v == 1)
        .unwrap_or(false);

    // Get strip offsets and byte counts to extract raw G4 data
    let offset_vals = decoder
        .get_tag_u64_vec(Tag::StripOffsets)
        .map_err(|e| IoError::DecodeError(format!("missing strip offsets: {}", e)))?;
    let count_vals = decoder
        .get_tag_u64_vec(Tag::StripByteCounts)
        .map_err(|e| IoError::DecodeError(format!("missing strip byte counts: {}", e)))?;

    let mut g4_data = Vec::new();
    for (offset, count) in offset_vals.iter().zip(count_vals.iter()) {
        let start = *offset as usize;
        let end = start + *count as usize;
        if end <= data.len() {
            g4_data.extend_from_slice(&data[start..end]);
        }
    }

    Ok(G4DataResult {
        data: g4_data,
        width,
        height,
        minisblack,
    })
}

/// Write TIFF with custom tags to memory
///
/// # See also
/// C Leptonica: `pixWriteMemTiffCustom()` in `tiffio.c`
pub fn write_tiff_custom_mem(
    pix: &Pix,
    compression: TiffCompression,
    tags: &TiffCustomTags,
) -> IoResult<Vec<u8>> {
    let mut cursor = std::io::Cursor::new(Vec::new());
    write_tiff_custom(pix, &mut cursor, compression, tags)?;
    Ok(cursor.into_inner())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_tiff_roundtrip_gray8() {
        let pix = Pix::new(10, 10, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        for y in 0..10 {
            for x in 0..10 {
                pix_mut.set_pixel(x, y, (x + y) * 10).unwrap();
            }
        }

        let pix: Pix = pix_mut.into();

        let mut buffer = Cursor::new(Vec::new());
        write_tiff(&pix, &mut buffer, TiffCompression::None).unwrap();

        buffer.set_position(0);
        let pix2 = read_tiff(buffer).unwrap();

        assert_eq!(pix2.width(), 10);
        assert_eq!(pix2.height(), 10);

        for y in 0..10 {
            for x in 0..10 {
                assert_eq!(pix2.get_pixel(x, y), pix.get_pixel(x, y));
            }
        }
    }

    #[test]
    fn test_tiff_roundtrip_rgb() {
        let pix = Pix::new(5, 5, PixelDepth::Bit32).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        pix_mut.set_rgb(0, 0, 255, 0, 0).unwrap();
        pix_mut.set_rgb(1, 1, 0, 255, 0).unwrap();
        pix_mut.set_rgb(2, 2, 0, 0, 255).unwrap();

        let pix: Pix = pix_mut.into();

        let mut buffer = Cursor::new(Vec::new());
        write_tiff(&pix, &mut buffer, TiffCompression::None).unwrap();

        buffer.set_position(0);
        let pix2 = read_tiff(buffer).unwrap();

        assert_eq!(pix2.get_rgb(0, 0), Some((255, 0, 0)));
        assert_eq!(pix2.get_rgb(1, 1), Some((0, 255, 0)));
        assert_eq!(pix2.get_rgb(2, 2), Some((0, 0, 255)));
    }

    #[test]
    fn test_tiff_compression_formats() {
        let pix = Pix::new(8, 8, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        for y in 0..8 {
            for x in 0..8 {
                pix_mut.set_pixel(x, y, ((x + y) * 16) % 256).unwrap();
            }
        }

        let pix: Pix = pix_mut.into();

        for compression in [TiffCompression::None, TiffCompression::PackBits] {
            let mut buffer = Cursor::new(Vec::new());
            write_tiff(&pix, &mut buffer, compression).unwrap();

            buffer.set_position(0);
            let pix2 = read_tiff(buffer).unwrap();

            assert_eq!(pix2.width(), 8);
            assert_eq!(pix2.height(), 8);
        }
    }

    #[test]
    fn test_tiff_multipage() {
        let pix1 = Pix::new(4, 4, PixelDepth::Bit8).unwrap();
        let pix2 = Pix::new(6, 6, PixelDepth::Bit8).unwrap();

        let pages: Vec<&Pix> = vec![&pix1, &pix2];
        let mut buffer = Cursor::new(Vec::new());
        write_tiff_multipage(&pages, &mut buffer, TiffCompression::None).unwrap();

        buffer.set_position(0);
        let count = tiff_page_count(buffer.clone()).unwrap();
        assert_eq!(count, 2);

        buffer.set_position(0);
        let loaded = read_tiff_multipage(buffer).unwrap();
        assert_eq!(loaded.len(), 2);
        assert_eq!(loaded[0].width(), 4);
        assert_eq!(loaded[1].width(), 6);
    }

    #[test]
    fn test_tiff_page_navigation() {
        let pix1 = Pix::new(4, 4, PixelDepth::Bit8).unwrap();
        let pix2 = Pix::new(8, 8, PixelDepth::Bit8).unwrap();

        let pages: Vec<&Pix> = vec![&pix1, &pix2];
        let mut buffer = Cursor::new(Vec::new());
        write_tiff_multipage(&pages, &mut buffer, TiffCompression::None).unwrap();

        buffer.set_position(0);
        let page0 = read_tiff_page(buffer.clone(), 0).unwrap();
        assert_eq!(page0.width(), 4);

        buffer.set_position(0);
        let page1 = read_tiff_page(buffer, 1).unwrap();
        assert_eq!(page1.width(), 8);
    }

    #[test]
    fn test_tiff_compression_enum() {
        assert_eq!(TiffCompression::None.to_image_format(), ImageFormat::Tiff);
        assert_eq!(TiffCompression::G4.to_image_format(), ImageFormat::TiffG4);
        assert_eq!(
            TiffCompression::from_image_format(ImageFormat::TiffLzw),
            Some(TiffCompression::Lzw)
        );
        assert_eq!(TiffCompression::from_image_format(ImageFormat::Png), None);
    }

    #[test]
    fn test_tiff_compression_detect_none() {
        let pix = Pix::new(8, 8, PixelDepth::Bit8).unwrap();
        let mut buffer = Cursor::new(Vec::new());
        write_tiff(&pix, &mut buffer, TiffCompression::None).unwrap();

        buffer.set_position(0);
        let compression = tiff_compression(buffer).unwrap();
        assert_eq!(compression, TiffCompression::None);
    }

    #[test]
    fn test_tiff_compression_detect_lzw() {
        let pix = Pix::new(8, 8, PixelDepth::Bit8).unwrap();
        let mut buffer = Cursor::new(Vec::new());
        write_tiff(&pix, &mut buffer, TiffCompression::Lzw).unwrap();

        buffer.set_position(0);
        let compression = tiff_compression(buffer).unwrap();
        assert_eq!(compression, TiffCompression::Lzw);
    }

    #[test]
    fn test_tiff_compression_detect_zip() {
        let pix = Pix::new(8, 8, PixelDepth::Bit8).unwrap();
        let mut buffer = Cursor::new(Vec::new());
        write_tiff(&pix, &mut buffer, TiffCompression::Zip).unwrap();

        buffer.set_position(0);
        let compression = tiff_compression(buffer).unwrap();
        assert_eq!(compression, TiffCompression::Zip);
    }

    #[test]
    fn test_write_tiff_append_single() {
        // Create an initial 2-page TIFF
        let pix1 = Pix::new(10, 10, PixelDepth::Bit8).unwrap();
        let pix2 = Pix::new(20, 20, PixelDepth::Bit8).unwrap();
        let pages: Vec<&Pix> = vec![&pix1, &pix2];
        let mut buffer = Cursor::new(Vec::new());
        write_tiff_multipage(&pages, &mut buffer, TiffCompression::None).unwrap();

        // Append a third page
        let pix3 = Pix::new(30, 30, PixelDepth::Bit8).unwrap();
        let existing = Cursor::new(buffer.into_inner());
        let mut output = Cursor::new(Vec::new());
        write_tiff_append(existing, &[&pix3], &mut output, TiffCompression::None).unwrap();

        // Verify 3 pages
        output.set_position(0);
        let count = tiff_page_count(output.clone()).unwrap();
        assert_eq!(count, 3);

        output.set_position(0);
        let loaded = read_tiff_multipage(output).unwrap();
        assert_eq!(loaded[0].width(), 10);
        assert_eq!(loaded[1].width(), 20);
        assert_eq!(loaded[2].width(), 30);
    }

    #[test]
    fn test_write_tiff_append_multiple() {
        // Create an initial single-page TIFF
        let pix1 = Pix::new(10, 10, PixelDepth::Bit8).unwrap();
        let mut buffer = Cursor::new(Vec::new());
        write_tiff(&pix1, &mut buffer, TiffCompression::Lzw).unwrap();

        // Append two more pages
        let pix2 = Pix::new(20, 20, PixelDepth::Bit8).unwrap();
        let pix3 = Pix::new(30, 30, PixelDepth::Bit8).unwrap();
        let existing = Cursor::new(buffer.into_inner());
        let mut output = Cursor::new(Vec::new());
        write_tiff_append(existing, &[&pix2, &pix3], &mut output, TiffCompression::Lzw).unwrap();

        // Verify 3 pages
        output.set_position(0);
        let loaded = read_tiff_multipage(output).unwrap();
        assert_eq!(loaded.len(), 3);
        assert_eq!(loaded[0].width(), 10);
        assert_eq!(loaded[1].width(), 20);
        assert_eq!(loaded[2].width(), 30);
    }

    #[test]
    fn test_write_tiff_append_empty_pages_error() {
        let pix = Pix::new(10, 10, PixelDepth::Bit8).unwrap();
        let mut buffer = Cursor::new(Vec::new());
        write_tiff(&pix, &mut buffer, TiffCompression::None).unwrap();

        let existing = Cursor::new(buffer.into_inner());
        let mut output = Cursor::new(Vec::new());
        let result = write_tiff_append(existing, &[], &mut output, TiffCompression::None);
        assert!(result.is_err());
    }
}