leptonica 0.1.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
//! Baseline detection
//!
//! This module provides functionality to detect text baselines in document images.
//! Baselines are useful for:
//! - Text line segmentation
//! - Local skew correction
//! - OCR preprocessing
//!
//! # Algorithm Overview
//!
//! 1. **Horizontal Projection**: Count pixels per row to create a projection histogram
//! 2. **Differential Signal**: Compute row-to-row differences to find transitions
//! 3. **Peak Detection**: Find peaks in the differential signal (baselines)
//! 4. **Endpoint Detection**: For each baseline, find left and right text boundaries

use crate::core::{Numa, Pix, PixelDepth, Pta};
use crate::morph::sequence::morph_sequence;
use crate::recog::skew::SkewDetectOptions;
use crate::recog::{RecogError, RecogResult};

/// Options for baseline detection
#[derive(Debug, Clone)]
pub struct BaselineOptions {
    /// Minimum text block width in pixels (default: 80)
    /// Blocks narrower than this are ignored
    pub min_block_width: u32,

    /// Peak threshold ratio (default: 80)
    /// Note: Currently the peak detection uses hardcoded thresholds matching
    /// the C version (maxval / 80 for peak, maxval / 100 for zero).
    /// This field is reserved for future use.
    pub peak_threshold: u32,

    /// Number of slices for local skew detection (default: 10)
    pub num_slices: u32,
}

impl Default for BaselineOptions {
    fn default() -> Self {
        Self {
            min_block_width: 80,
            peak_threshold: 80,
            num_slices: 10,
        }
    }
}

impl BaselineOptions {
    /// Create new options with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the minimum block width
    pub fn with_min_block_width(mut self, width: u32) -> Self {
        self.min_block_width = width;
        self
    }

    /// Set the peak threshold ratio
    pub fn with_peak_threshold(mut self, threshold: u32) -> Self {
        self.peak_threshold = threshold;
        self
    }

    /// Set the number of slices for local skew
    pub fn with_num_slices(mut self, slices: u32) -> Self {
        self.num_slices = slices;
        self
    }

    /// Validate options
    fn validate(&self) -> RecogResult<()> {
        if self.min_block_width == 0 {
            return Err(RecogError::InvalidParameter(
                "min_block_width must be positive".to_string(),
            ));
        }
        if self.peak_threshold == 0 || self.peak_threshold > 100 {
            return Err(RecogError::InvalidParameter(
                "peak_threshold must be between 1 and 100".to_string(),
            ));
        }
        if self.num_slices < 2 || self.num_slices > 20 {
            return Err(RecogError::InvalidParameter(
                "num_slices must be between 2 and 20".to_string(),
            ));
        }
        Ok(())
    }
}

/// Result of baseline detection
#[derive(Debug, Clone)]
pub struct BaselineResult {
    /// Y coordinates of detected baselines
    pub baselines: Vec<i32>,

    /// Optional endpoints for each baseline: (x1, y1, x2, y2)
    /// x1, y1 = left endpoint; x2, y2 = right endpoint
    pub endpoints: Option<Vec<(i32, i32, i32, i32)>>,
}

// Constants for peak detection (matching C version's baseline.c)
// Note: These are used as divisors (maxval / ratio), NOT multipliers.
// C version: peakthresh = (l_int32)maxval / PeakThresholdRatio
// C version: zerothresh = (l_int32)maxval / ZeroThresholdRatio
const MIN_DIST_FROM_PEAK: i32 = 30;
const PEAK_THRESHOLD_RATIO: i32 = 80;
const ZERO_THRESHOLD_RATIO: i32 = 100;

/// Find baselines in a binary image
///
/// # Arguments
/// * `pix` - Input image (should be binary, 1 bpp)
/// * `options` - Detection options
///
/// # Returns
/// BaselineResult containing y-coordinates of baselines
///
/// # Example
/// ```no_run
/// use leptonica::recog::baseline::{find_baselines, BaselineOptions};
/// use leptonica::core::{Pix, PixelDepth};
///
/// let pix = Pix::new(500, 300, PixelDepth::Bit1).unwrap();
/// let result = find_baselines(&pix, &BaselineOptions::default()).unwrap();
/// for y in &result.baselines {
///     println!("Baseline at y = {}", y);
/// }
/// ```
pub fn find_baselines(pix: &Pix, options: &BaselineOptions) -> RecogResult<BaselineResult> {
    options.validate()?;

    // Ensure binary
    let binary = ensure_binary(pix)?;

    let h = binary.height();

    // Step 1: Morphological preprocessing to consolidate text characters
    // C版: pix1 = pixMorphSequence(pixs, "c25.1 + e15.1", 0)
    // Close horizontally to connect characters, then erode to clean noise
    let preprocessed = match morph_sequence(&binary, "c25.1 + e15.1") {
        Ok(p) => p,
        Err(_) => binary.deep_clone(), // Fall back to original if morph fails
    };

    // Step 2: Compute horizontal projection (row sums) on preprocessed image
    let row_sums = compute_row_sums(&preprocessed);

    // Step 3: Compute differential (row-to-row differences)
    let diff = compute_differential(&row_sums);

    // Step 4: Find peaks in differential signal
    let baselines = find_peaks(&diff, options.peak_threshold);

    // Step 5: Find endpoints for each baseline using the original binary image
    let endpoints = find_endpoints(&binary, &baselines, options.min_block_width);

    // Filter baselines without valid endpoints
    let (filtered_baselines, filtered_endpoints) = filter_baselines(baselines, endpoints, h);

    Ok(BaselineResult {
        baselines: filtered_baselines,
        endpoints: Some(filtered_endpoints),
    })
}

/// Get local skew angles for vertical slices of the image (simple variant).
///
/// # Arguments
/// * `pix` - Input image
/// * `num_slices` - Number of vertical slices
/// * `sweep_range` - Angle range for skew detection (degrees)
///
/// # Returns
/// Vector of skew angles, one per slice
#[allow(dead_code)]
fn get_slice_skew_angles(pix: &Pix, num_slices: u32, sweep_range: f32) -> RecogResult<Vec<f32>> {
    if !(2..=20).contains(&num_slices) {
        return Err(RecogError::InvalidParameter(
            "num_slices must be between 2 and 20".to_string(),
        ));
    }

    let binary = ensure_binary(pix)?;
    let h = binary.height();
    let slice_height = h / num_slices;

    if slice_height < 10 {
        return Err(RecogError::ImageTooSmall {
            min_width: pix.width(),
            min_height: num_slices * 10,
            actual_width: pix.width(),
            actual_height: h,
        });
    }

    let mut angles = Vec::with_capacity(num_slices as usize);
    let skew_options = SkewDetectOptions::default()
        .with_sweep_range(sweep_range)
        .with_sweep_reduction(2)
        .with_bs_reduction(1);

    // Add overlap (50% of slice height)
    let overlap = slice_height / 2;

    for i in 0..num_slices {
        let y_start = if i == 0 {
            0
        } else {
            (i * slice_height).saturating_sub(overlap)
        };
        let y_end = if i == num_slices - 1 {
            h
        } else {
            ((i + 1) * slice_height + overlap).min(h)
        };

        // Extract slice
        let slice = extract_horizontal_slice(&binary, y_start, y_end)?;

        // Detect skew for this slice
        match crate::recog::skew::find_skew(&slice, &skew_options) {
            Ok(result) => angles.push(result.angle),
            Err(_) => angles.push(0.0), // Default to 0 if detection fails
        }
    }

    Ok(angles)
}

/// Apply local deskew based on baseline analysis (internal helper).
///
/// This corrects for varying skew across the page (keystone effect).
#[allow(dead_code)]
fn deskew_local_baseline_opts(
    pix: &Pix,
    options: &BaselineOptions,
    skew_options: &SkewDetectOptions,
) -> RecogResult<Pix> {
    options.validate()?;
    skew_options.validate()?;

    let binary = ensure_binary(pix)?;

    // Get local skew angles
    let angles = get_slice_skew_angles(&binary, options.num_slices, skew_options.sweep_range)?;

    // If all angles are similar, just do global deskew
    let angle_range = angles.iter().cloned().fold(f32::NAN, f32::max)
        - angles.iter().cloned().fold(f32::NAN, f32::min);

    if angle_range < 0.5 || angles.is_empty() {
        // Use average angle for global correction
        let avg_angle: f32 = angles.iter().sum::<f32>() / angles.len().max(1) as f32;
        return crate::recog::skew::deskew_by_angle(pix, avg_angle);
    }

    // Apply local correction using vertical shear interpolation
    apply_local_deskew(pix, &angles)
}

// ============================================================================
// Public API (C-compatible signatures)
// ============================================================================

/// Deskew an image using local skew detection.
///
/// Divides the image into `nslice` horizontal slices, detects the skew angle
/// for each slice independently, and applies a varying correction.
///
/// # Arguments
/// * `pix` - Input image (1 or 8 bpp)
/// * `nslice` - Number of horizontal slices (2–20)
/// * `reduction` - Subsampling factor for angle computation (1, 2, or 4)
/// * `redsweep` - Sweep reduction factor (1, 2, 4, or 8)
/// * `redsearch` - Binary-search reduction factor (1, 2, 4, or 8)
/// * `sweep_range` - Half-angle range for sweep in degrees
/// * `sweep_delta` - Step size for sweep in degrees
/// * `min_bs_delta` - Minimum improvement for binary search termination
///
/// # Errors
///
/// Returns an error if parameters are invalid or processing fails.
#[allow(clippy::too_many_arguments)]
pub fn deskew_local(
    pix: &Pix,
    nslice: u32,
    reduction: u32,
    redsweep: u32,
    redsearch: u32,
    sweep_range: f32,
    sweep_delta: f32,
    min_bs_delta: f32,
) -> RecogResult<Pix> {
    // Use defaults for out-of-range values (match C version behaviour)
    let nslice = if !(2..=20).contains(&nslice) {
        10
    } else {
        nslice
    };
    let sweep_red = match redsweep {
        1 | 2 | 4 | 8 => redsweep,
        _ => 2,
    };
    let _ = redsearch; // used indirectly via get_local_skew_angles default
    let sweep_range = if sweep_range <= 0.0 { 7.0 } else { sweep_range };
    let sweep_delta = if sweep_delta <= 0.0 { 1.0 } else { sweep_delta };
    let min_bs_delta = if min_bs_delta <= 0.0 {
        0.01
    } else {
        min_bs_delta
    };
    // reduction is passed through to get_local_skew_angles (overrides redsweep)
    let red = match reduction {
        1 | 2 | 4 | 8 => reduction,
        _ => sweep_red,
    };

    // Get per-raster-line angle estimates via linear fit over slice samples
    let (_, a, b) =
        get_local_skew_angles(pix, nslice, red, sweep_range, sweep_delta, min_bs_delta)?;

    // Compute one angle per slice from the linear fit (y = slice centre)
    let h = pix.height() as f32;
    let angles: Vec<f32> = (0..nslice as usize)
        .map(|i| {
            let y_center = (i as f32 + 0.5) / nslice as f32 * h;
            a * y_center + b
        })
        .collect();

    // Apply interpolated local shear correction
    apply_local_deskew(pix, &angles)
}

/// Compute a set of control points for a local skew transform.
///
/// Returns a [`Pta`] containing `(nslice × ny)` control points that map
/// positions in the original image to deskewed positions.
///
/// # Arguments
/// * `nslice` - Number of horizontal slices
/// * `ny` - Number of vertical sample points per slice
/// * `reduction` - Subsampling factor used when the angles were measured
/// * `angles` - Skew angle (degrees) for each slice; length must equal `nslice`
/// * `cx` - X coordinate of the image centre (used as pivot for shear)
/// * `cy` - Y coordinate of the image centre (used as pivot for shear)
///
/// # Errors
///
/// Returns an error if `angles.len() != nslice as usize`.
pub fn get_local_skew_transform(
    nslice: u32,
    ny: u32,
    reduction: u32,
    angles: &[f32],
    cx: f32,
    cy: f32,
) -> RecogResult<Pta> {
    if angles.len() != nslice as usize {
        return Err(RecogError::InvalidParameter(format!(
            "angles length {} must equal nslice {}",
            angles.len(),
            nslice
        )));
    }
    if nslice == 0 || ny == 0 {
        return Err(RecogError::InvalidParameter(
            "nslice and ny must be positive".to_string(),
        ));
    }

    // Total image height estimate: cy is the vertical centre so h ≈ 2 * cy
    // (scaled by reduction to recover original-resolution coordinates)
    let h_full = cy * 2.0 * reduction as f32;
    let slice_h = h_full / nslice as f32;

    let mut pta = Pta::with_capacity(nslice as usize * ny as usize);

    for (i, &angle_deg) in angles.iter().enumerate() {
        let tan_a = angle_deg.to_radians().tan();
        for j in 0..ny as usize {
            // y position at the centre of this sample within the slice
            let y_frac = (j as f32 + 0.5) / ny as f32;
            let y = (i as f32 + y_frac) * slice_h;
            // Horizontal shear offset relative to the vertical centre (cy)
            let x_shift = (y - cy) * tan_a;
            pta.push(cx + x_shift, y);
        }
    }

    Ok(pta)
}

/// Compute per-slice skew angles for a document image.
///
/// Divides `pix` into `nslice` horizontal slices and runs sweep-and-search
/// skew detection on each slice. Slices overlap by 50% to reduce edge effects.
///
/// A linear least-squares fit over the (y_center, angle) sample points is used
/// to produce a smooth angle estimate for every raster line.
///
/// # Returns
/// A tuple `(angles, slope, intercept)` where `angles` is a [`Numa`] of
/// per-raster-line angle estimates (length = image height), `slope` is the
/// coefficient `a` in `angle = a·y + b`, and `intercept` is `b`.
///
/// # Errors
///
/// Returns an error if the image is too small or no reliable skew samples
/// could be collected.
pub fn get_local_skew_angles(
    pix: &Pix,
    nslice: u32,
    reduction: u32,
    sweep_range: f32,
    sweep_delta: f32,
    min_bs_delta: f32,
) -> RecogResult<(Numa, f32, f32)> {
    // Apply defaults for 0 / out-of-range values (matching C version behaviour)
    let nslice = if !(2..=20).contains(&nslice) {
        10
    } else {
        nslice
    };
    let sweep_reduction = match reduction {
        1 | 2 | 4 | 8 => reduction,
        _ => 2,
    };
    let bs_reduction = (sweep_reduction / 2).max(1);
    let sweep_range = if sweep_range <= 0.0 { 7.0 } else { sweep_range };
    let sweep_delta = if sweep_delta <= 0.0 { 1.0 } else { sweep_delta };
    let min_bs_delta = if min_bs_delta <= 0.0 {
        0.01
    } else {
        min_bs_delta
    };

    let binary = ensure_binary(pix)?;
    let w = binary.width();
    let h = binary.height();

    let hs = (h / nslice).max(1);
    let ovlap = hs / 2; // 50 % overlap (OverlapFraction = 0.5 in C version)

    let skew_opts = crate::recog::skew::SkewDetectOptions {
        sweep_range,
        sweep_delta,
        min_bs_delta,
        sweep_reduction,
        bs_reduction,
    };

    // Minimum confidence for a sample to be included (MinAllowedConfidence = 1.0)
    const MIN_CONF: f32 = 1.0;

    // Collect (y_center, angle) pairs with sufficient confidence
    let mut pts: Vec<(f32, f32)> = Vec::new();
    for i in 0..nslice {
        let y_start = if i == 0 {
            0
        } else {
            (hs * i).saturating_sub(ovlap)
        };
        let y_end = if i == nslice - 1 {
            h
        } else {
            (hs * (i + 1) + ovlap).min(h)
        };
        if y_end <= y_start {
            continue;
        }
        let y_center = (y_start + y_end) as f32 / 2.0;

        let slice = binary.clip_rectangle(0, y_start, w, y_end - y_start)?;
        if let Ok(result) = crate::recog::skew::find_skew(&slice, &skew_opts)
            && result.confidence >= MIN_CONF
        {
            pts.push((y_center, result.angle));
        }
    }

    // Linear least-squares fit: angle = a * y + b
    let (a, b) = if pts.len() >= 2 {
        linear_lsf(&pts)
    } else {
        // Not enough data — use zero skew
        (0.0_f32, 0.0_f32)
    };

    // Build per-raster-line Numa
    let mut naskew = Numa::with_capacity(h as usize);
    for i in 0..h {
        naskew.push(a * i as f32 + b);
    }

    Ok((naskew, a, b))
}

// ============================================================================
// Internal functions
// ============================================================================

/// Linear least-squares fit through a set of (x, y) points.
///
/// Returns `(a, b)` such that `y ≈ a·x + b` minimises the sum of squared
/// residuals. Falls back to `(0, mean_y)` when the denominator is near zero.
fn linear_lsf(pts: &[(f32, f32)]) -> (f32, f32) {
    let n = pts.len() as f32;
    let sum_x: f32 = pts.iter().map(|&(x, _)| x).sum();
    let sum_y: f32 = pts.iter().map(|&(_, y)| y).sum();
    let sum_xx: f32 = pts.iter().map(|&(x, _)| x * x).sum();
    let sum_xy: f32 = pts.iter().map(|&(x, y)| x * y).sum();
    let denom = n * sum_xx - sum_x * sum_x;
    if denom.abs() < 1e-10 {
        return (0.0, sum_y / n);
    }
    let a = (n * sum_xy - sum_x * sum_y) / denom;
    let b = (sum_y - a * sum_x) / n;
    (a, b)
}

/// Ensure image is binary
fn ensure_binary(pix: &Pix) -> RecogResult<Pix> {
    match pix.depth() {
        PixelDepth::Bit1 => Ok(pix.deep_clone()),
        PixelDepth::Bit8 => {
            let w = pix.width();
            let h = pix.height();
            let binary = Pix::new(w, h, PixelDepth::Bit1)?;
            let mut binary_mut = binary.try_into_mut().unwrap();

            for y in 0..h {
                for x in 0..w {
                    let val = pix.get_pixel_unchecked(x, y);
                    let bit = if val < 128 { 1 } else { 0 };
                    binary_mut.set_pixel_unchecked(x, y, bit);
                }
            }
            Ok(binary_mut.into())
        }
        _ => Err(RecogError::UnsupportedDepth {
            expected: "1 or 8 bpp",
            actual: pix.depth().bits(),
        }),
    }
}

/// Compute row sums (horizontal projection)
fn compute_row_sums(pix: &Pix) -> Vec<u32> {
    let w = pix.width();
    let h = pix.height();
    let mut sums = Vec::with_capacity(h as usize);

    for y in 0..h {
        let mut sum = 0u32;
        for x in 0..w {
            let val = pix.get_pixel_unchecked(x, y);
            if val != 0 {
                sum += 1;
            }
        }
        sums.push(sum);
    }

    sums
}

/// Compute differential signal (difference between adjacent rows)
fn compute_differential(row_sums: &[u32]) -> Vec<i32> {
    if row_sums.len() < 2 {
        return Vec::new();
    }

    let mut diff = Vec::with_capacity(row_sums.len() - 1);
    for i in 0..row_sums.len() - 1 {
        diff.push(row_sums[i] as i32 - row_sums[i + 1] as i32);
    }
    diff
}

/// Find peaks in differential signal
///
/// Uses the same threshold calculation as C version's pixFindBaselinesGen:
///   peakthresh = maxval / PeakThresholdRatio  (divisor, not multiplier)
///   zerothresh = maxval / ZeroThresholdRatio   (divisor, not multiplier)
fn find_peaks(diff: &[i32], _threshold_ratio: u32) -> Vec<i32> {
    if diff.is_empty() {
        return Vec::new();
    }

    // Find maximum value
    let max_val = diff.iter().cloned().max().unwrap_or(0);
    if max_val <= 0 {
        return Vec::new();
    }

    // C版: peakthresh = (l_int32)maxval / PeakThresholdRatio;  (division!)
    // C版: zerothresh = (l_int32)maxval / ZeroThresholdRatio;   (division!)
    let peak_thresh = max_val / PEAK_THRESHOLD_RATIO;
    let zero_thresh = max_val / ZERO_THRESHOLD_RATIO;

    let mut baselines = Vec::new();
    let mut in_peak = false;
    let mut max_in_peak = 0i32;
    let mut max_loc = 0i32;
    let mut min_to_search = 0i32;

    for (i, &val) in diff.iter().enumerate() {
        let i = i as i32;

        if !in_peak {
            if val > peak_thresh {
                // Transition to in-peak
                in_peak = true;
                min_to_search = i + MIN_DIST_FROM_PEAK;
                max_in_peak = val;
                max_loc = i;
            }
        } else {
            // Looking for peak maximum
            if val > max_in_peak {
                max_in_peak = val;
                max_loc = i;
                min_to_search = i + MIN_DIST_FROM_PEAK;
            } else if i >= min_to_search && val <= zero_thresh {
                // Found end of peak, record baseline
                in_peak = false;
                baselines.push(max_loc);
            }
        }
    }

    // Handle case where peak extends to end
    if in_peak {
        baselines.push(max_loc);
    }

    baselines
}

/// Find left and right endpoints for each baseline
fn find_endpoints(
    pix: &Pix,
    baselines: &[i32],
    min_width: u32,
) -> Vec<Option<(i32, i32, i32, i32)>> {
    let w = pix.width() as i32;
    let h = pix.height() as i32;

    baselines
        .iter()
        .map(|&y| {
            if y < 0 || y >= h {
                return None;
            }

            // Find leftmost and rightmost black pixels near baseline
            let search_range = 5; // Search ±5 rows
            let mut left_x = w;
            let mut right_x = 0i32;

            for dy in -search_range..=search_range {
                let sy = y + dy;
                if sy < 0 || sy >= h {
                    continue;
                }

                for x in 0..w {
                    let val = pix.get_pixel_unchecked(x as u32, sy as u32);
                    if val != 0 {
                        left_x = left_x.min(x);
                        right_x = right_x.max(x);
                    }
                }
            }

            if right_x - left_x >= min_width as i32 {
                Some((left_x, y, right_x, y))
            } else {
                None
            }
        })
        .collect()
}

/// Filter baselines that don't have valid endpoints
#[allow(clippy::type_complexity)]
fn filter_baselines(
    baselines: Vec<i32>,
    endpoints: Vec<Option<(i32, i32, i32, i32)>>,
    _max_y: u32,
) -> (Vec<i32>, Vec<(i32, i32, i32, i32)>) {
    let mut filtered_baselines = Vec::new();
    let mut filtered_endpoints = Vec::new();

    for (baseline, endpoint) in baselines.into_iter().zip(endpoints.into_iter()) {
        if let Some(ep) = endpoint {
            filtered_baselines.push(baseline);
            filtered_endpoints.push(ep);
        }
    }

    (filtered_baselines, filtered_endpoints)
}

/// Extract a horizontal slice from an image
#[allow(dead_code)]
fn extract_horizontal_slice(pix: &Pix, y_start: u32, y_end: u32) -> RecogResult<Pix> {
    let w = pix.width();
    let new_h = y_end - y_start;

    if new_h == 0 {
        return Err(RecogError::InvalidParameter(
            "slice height is zero".to_string(),
        ));
    }

    let slice = Pix::new(w, new_h, pix.depth())?;
    let mut slice_mut = slice.try_into_mut().unwrap();

    for y in 0..new_h {
        for x in 0..w {
            let val = pix.get_pixel_unchecked(x, y_start + y);
            slice_mut.set_pixel_unchecked(x, y, val);
        }
    }

    Ok(slice_mut.into())
}

/// Apply local deskew using interpolated shear
#[allow(dead_code)]
fn apply_local_deskew(pix: &Pix, angles: &[f32]) -> RecogResult<Pix> {
    let w = pix.width();
    let h = pix.height();
    let num_slices = angles.len();

    if num_slices == 0 {
        return Ok(pix.deep_clone());
    }

    let slice_height = h as f32 / num_slices as f32;

    let result = Pix::new(w, h, pix.depth())?;
    let mut result_mut = result.try_into_mut().unwrap();

    // Fill with background
    for y in 0..h {
        for x in 0..w {
            result_mut.set_pixel_unchecked(x, y, 0);
        }
    }

    // Apply varying shear based on interpolated angle
    for y in 0..h {
        // Determine which slice and interpolation weight
        let slice_pos = y as f32 / slice_height;
        let slice_idx = (slice_pos as usize).min(num_slices - 1);
        let next_idx = (slice_idx + 1).min(num_slices - 1);
        let t = slice_pos - slice_idx as f32;

        // Interpolate angle
        let angle = angles[slice_idx] * (1.0 - t) + angles[next_idx] * t;
        let tan_a = angle.to_radians().tan();

        for x in 0..w {
            let val = pix.get_pixel_unchecked(x, y);
            if val != 0 {
                // Apply horizontal shear
                let shear = (x as f32 - w as f32 / 2.0) * tan_a;
                let new_x = (x as f32 + shear).round() as i32;

                if new_x >= 0 && new_x < w as i32 {
                    result_mut.set_pixel_unchecked(new_x as u32, y, val);
                }
            }
        }
    }

    Ok(result_mut.into())
}

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

    fn create_text_like_image(w: u32, h: u32, num_lines: u32, line_height: u32) -> Pix {
        let pix = Pix::new(w, h, PixelDepth::Bit1).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        let spacing = h / (num_lines + 1);

        for line in 1..=num_lines {
            let y_base = line * spacing;
            // Draw a "text line" as a horizontal band
            for dy in 0..line_height {
                let y = y_base + dy;
                if y < h {
                    for x in (w / 10)..(w * 9 / 10) {
                        pix_mut.set_pixel_unchecked(x, y, 1);
                    }
                }
            }
        }

        pix_mut.into()
    }

    #[test]
    fn test_baseline_options_default() {
        let opts = BaselineOptions::default();
        assert_eq!(opts.min_block_width, 80);
        assert_eq!(opts.peak_threshold, 80);
        assert_eq!(opts.num_slices, 10);
    }

    #[test]
    fn test_baseline_options_validation() {
        let opts = BaselineOptions::default();
        assert!(opts.validate().is_ok());

        let invalid = BaselineOptions::default().with_min_block_width(0);
        assert!(invalid.validate().is_err());

        let invalid = BaselineOptions::default().with_num_slices(1);
        assert!(invalid.validate().is_err());
    }

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

        // Fill row 2 with black pixels
        for x in 0..10 {
            pix_mut.set_pixel_unchecked(x, 2, 1);
        }

        let pix: Pix = pix_mut.into();
        let sums = compute_row_sums(&pix);

        assert_eq!(sums.len(), 5);
        assert_eq!(sums[0], 0);
        assert_eq!(sums[1], 0);
        assert_eq!(sums[2], 10);
        assert_eq!(sums[3], 0);
        assert_eq!(sums[4], 0);
    }

    #[test]
    fn test_compute_differential() {
        let row_sums = vec![0, 0, 10, 0, 0];
        let diff = compute_differential(&row_sums);

        assert_eq!(diff.len(), 4);
        assert_eq!(diff[0], 0); // 0 - 0
        assert_eq!(diff[1], -10); // 0 - 10
        assert_eq!(diff[2], 10); // 10 - 0
        assert_eq!(diff[3], 0); // 0 - 0
    }

    #[test]
    fn test_find_baselines() {
        let pix = create_text_like_image(400, 300, 5, 10);
        let opts = BaselineOptions::default().with_min_block_width(50);

        let result = find_baselines(&pix, &opts).unwrap();

        // Should find approximately 5 baselines
        assert!(!result.baselines.is_empty());
        assert!(result.baselines.len() <= 6);
    }

    #[test]
    fn test_extract_horizontal_slice() {
        let pix = Pix::new(100, 100, PixelDepth::Bit1).unwrap();
        let slice = extract_horizontal_slice(&pix, 20, 40).unwrap();

        assert_eq!(slice.width(), 100);
        assert_eq!(slice.height(), 20);
    }

    #[test]
    fn test_get_slice_skew_angles() {
        let pix = create_text_like_image(400, 400, 10, 10);
        let angles = get_slice_skew_angles(&pix, 4, 5.0).unwrap();

        assert_eq!(angles.len(), 4);
        // All angles should be near zero for horizontal lines
        for angle in angles {
            assert!(angle.abs() < 2.0);
        }
    }

    #[test]
    fn test_get_local_skew_angles_returns_numa() {
        let pix = create_text_like_image(400, 400, 10, 10);
        // Numa length equals image height (one angle per raster line)
        let (angles, slope, _intercept) =
            get_local_skew_angles(&pix, 4, 2, 7.0, 1.0, 0.01).unwrap();
        assert_eq!(angles.len(), pix.height() as usize);
        // For near-horizontal lines, the slope should be tiny
        assert!(slope.abs() < 1.0);
    }

    #[test]
    fn test_deskew_local_new_api() {
        let pix = create_text_like_image(400, 400, 10, 10);
        let result = deskew_local(&pix, 4, 2, 2, 1, 7.0, 1.0, 0.01).unwrap();
        assert_eq!(result.width(), pix.width());
        assert_eq!(result.height(), pix.height());
    }

    #[test]
    fn test_get_local_skew_transform() {
        let angles = vec![0.5f32, 0.3, 0.1, -0.1];
        let pta = get_local_skew_transform(4, 1, 2, &angles, 200.0, 200.0).unwrap();
        // Should produce nslice * ny = 4 * 1 = 4 points
        assert_eq!(pta.len(), 4);
    }
}