#!/usr/bin/perl
#THE WORKING VERSION

# Rotoscope create new lines of dots, reference images in $img_dir
# Or cycle through CSVs and add dots to current.
# Key	Action
# S	Save current CSV
# C	Create a new, empty CSV and make it current

# N	load the next CSV
# P	load the previous CSV

# H	Hide/show dots from other CSV files; current CSV dots stay visible
# Left arrow	   Previous image
# Right arrow   Next image
# Mouse click   Add a dot to the current CSV
# Change $img_dir to directory containing single or many images for background.
use strict;
use warnings;
use Tk;
use Tk::JPEG;
use Tk::PNG;

use feature "say";
#use Time::HiRes qw(time);
my @points;
my @other_points;
#CHANGE image directory here
###########
#my $img_dir  = 'bg_forest';
#my $save_dir = "PATHS/$img_dir";
#my $base_file = '';
#mkdir $save_dir unless -d $save_dir;
############
#setup browser

# Directory setup browser
use Cwd qw(getcwd abs_path);
use File::Path qw(make_path);
use File::Spec;

my $img_dir   = 'bg_forest';
my $save_dir  = "PATHS/$img_dir";
my $base_file = '';

my $chosen_img  = '';
my $chosen_save = '';
my $browse_dir  = getcwd();
my $proceed     = 0;
#my $file_num =0;
my $setup = MainWindow->new;
$setup->title('Select Directories');
$setup->geometry('1100x800');

my $font = ['Helvetica', 18];

$setup->Label(
    -text => 'Select image and save directories',
    -font => ['Helvetica', 22],
)->grid(-row => 0, -column => 0, -columnspan => 3, -pady => 10);

my $dir_entry = $setup->Entry(
    -textvariable => \$browse_dir,
    -font => $font,
)->grid(-row => 1, -column => 0, -columnspan => 2, -sticky => 'ew');

$setup->Button(
    -text => 'GO UP',
    -font => $font,
    -command => sub {
        my $parent = File::Spec->catdir(
            $browse_dir, File::Spec->updir
        );
        $browse_dir = abs_path($parent) || $browse_dir;
        refresh_dirs();
    },
)->grid(-row => 1, -column => 2, -sticky => 'ew', -padx => 5);

my $listbox = $setup->Scrolled(
    'Listbox',
    -font => $font,
    -scrollbars => 'se',
    -width => 90,
    -height => 20,
)->grid(-row => 2, -column => 0, -columnspan => 3, -sticky => 'nsew');

$setup->Label(
    -text => 'Image directory:',
    -font => $font,
)->grid(-row => 3, -column => 0, -sticky => 'w');

$setup->Entry(
    -textvariable => \$chosen_img,
    -font => $font,
)->grid(-row => 3, -column => 1, -sticky => 'ew');

$setup->Button(
    -text => 'Use for Images',
    -font => $font,
    -command => sub { $chosen_img = $browse_dir },
)->grid(-row => 3, -column => 2, -padx => 5);

$setup->Label(
    -text => 'Save directory:',
    -font => $font,
)->grid(-row => 4, -column => 0, -sticky => 'w');

$setup->Entry(
    -textvariable => \$chosen_save,
    -font => $font,
)->grid(-row => 4, -column => 1, -sticky => 'ew');
#-------------

$setup->Button(
    -text => 'Use for Saving Paths',
    -font => $font,
    -command => sub {
        if ($chosen_save eq '') {
            $chosen_save = $browse_dir;
        }
    },
)->grid(-row => 4, -column => 2, -padx => 5);

#========================

$setup->Button(
    -text => 'Continue',
    -font => $font,
    -command => sub {
        unless (-d $chosen_img) {
            print "Image directory does not exist: $chosen_img\n";
            return;
        }

        unless ($chosen_save ne '') {
            print "Enter a save directory\n";
            return;
        }

        # Convert both selections to absolute paths first.
        my $new_img  = abs_path($chosen_img);
        my $new_save = File::Spec->rel2abs($chosen_save);

        # Create the save directory if necessary.
        unless (-d $new_save) {
            eval { make_path($new_save) };

            if ($@ || !-d $new_save) {
                print "Cannot create save directory: $new_save\n";
                print "$@\n" if $@;
                return;
            }
        }

        $img_dir  = $new_img;
        $save_dir = abs_path($new_save);

        # Show the resolved save directory in the entry.
        $chosen_save = $save_dir;

        print "Image directory: [$img_dir]\n";
        print "Save directory: [$save_dir]\n";

        $proceed = 1;
        $setup->destroy;
    },
)->grid(-row => 5, -column => 1, -pady => 10);





#============
$setup->Button(
    -text => 'QUIT',
    -font => $font,
    -command => sub { $setup->destroy },
)->grid(-row => 5, -column => 2);

$setup->gridColumnconfigure(1, -weight => 1);
$setup->gridRowconfigure(2, -weight => 1);

$listbox->bind('<Double-Button-1>', sub {
    my $selection = $listbox->get('active');
    return unless defined $selection;

    my $path = File::Spec->catdir($browse_dir, $selection);

    if (-d $path) {
        $browse_dir = abs_path($path) || $path;
        refresh_dirs();
    }
});

sub refresh_dirs {
    $listbox->delete(0, 'end');

    opendir(my $dh, $browse_dir) or return;

    my @contents = sort { lc($a) cmp lc($b) }
        grep { $_ ne '.' && $_ ne '..' } readdir($dh);

    closedir($dh);

    for my $item (@contents) {
        my $path = File::Spec->catfile($browse_dir, $item);
        $listbox->insert('end', $item);
        $listbox->itemconfigure(
            'end',
            -foreground => (-d $path ? 'blue' : 'black')
        );
    }
}

refresh_dirs();
MainLoop;

exit unless $proceed;
#say "All saved .csvs are relative to top left, change them later with csv-tool";
# Create the save directory if necessary.
make_path($save_dir) unless -d $save_dir;

# Load background images.
opendir(my $dh, $img_dir)
    or die "Cannot open image directory $img_dir: $!";

my @images = sort grep { /\.(?:jpe?g|png)$/i } readdir($dh);
closedir($dh);

die "No images in $img_dir\n" unless @images;

############
# Use the first image as a fixed background.
opendir($dh, $img_dir) or die "Cannot open $img_dir: $!";
@images = sort grep { /\.(?:jpe?g|png)$/i } readdir($dh);
closedir $dh;
die "No images in $img_dir\n" unless @images;

my $mw = MainWindow->new;
my $photo = $mw->Photo(-file => "$img_dir/$images[0]");
my ($W, $H) = ($photo->width, $photo->height);

# Create the directory for this image collection.

#mkdir 'PATHS' unless -d 'PATHS';
#mkdir $save_dir unless -d $save_dir;

####################
# Load existing CSV files without renaming them.
print "SAVE DIR: [$save_dir]\n";
print "CSV MATCHES: ", join(", ", glob("$save_dir/points_*.csv")), "\n";
my @csv_files = sort glob("$save_dir/points_*.csv");

# Create the first CSV if none exist.
if (!@csv_files) {
    my $file = "$save_dir/points_001.csv";
    open my $fh, '>', $file or die "Cannot create $file: $!";
    close $fh;
    @csv_files = ($file);
}
#######
my $csv_index = 0;
my $current_file = '';
my $show_points = 1;
my $point_colour = 'red';
my $index = 0;
my $reverse_on_save = 0;   # when true, reverse point order on Save / New
my $merge_mode = '';       # '' | 'front' | 'back'  – temporary add-to-base mode

# Density edit / key points support
my @key_points;            # original manually-placed (pre-smooth) points
my $has_smoothed = 0;      # true after a Smooth Line (until load/undo)
my $density_mode = 0;      # 1 while drawing selection rectangle
my ($sel_x1, $sel_y1, $sel_x2, $sel_y2);
my $sel_rect;              # canvas id of selection rectangle


# Smooth line settings
my $num_points = 10;
my $smooth_res = 50;
my @points_before_smooth;   # backup for Undo
my @spline_preview;        # last spline for faint drawing
my $points_entry;          # widget reference for colour feedback
$mw->title('Point Collector');

my $status = $mw->Label(
    -text       => '',
    -font       => ['Helvetica', 14],
    -anchor     => 'w',
)->pack(-fill => 'x');

my $canvas = $mw->Canvas(
    -width      => $W,
    -height     => $H,
    -background => 'black',
)->pack;

# Load the first CSV.
load_csv();
draw_image();
$canvas->CanvasBind(
    '<Button-1>' => [ \&add_point, Ev('x'), Ev('y') ]
);

# Clicks on the main window (status bar etc.) also release entry focus
$mw->bind('<Button-1>', sub { $mw->focus if $points_entry; });

$mw->bind('<Right>' => sub {
    return if $index >= $#images;
    $index++;
    draw_image();
});

$mw->bind('<Left>' => sub {
    return if $index <= 0;
    $index--;
    draw_image();
});
##################
$mw->bind('<KeyPress-KP_Right>' => sub {
    return if $index >= $#images;
    $index++;
    draw_image();
});

$mw->bind('<KP_Left>' => sub {
    return if $index <= 0;
    $index--;
    draw_image();
});

#$mw->bind('<Any-KeyPress>' => sub {
#    my $w = shift;
#    print "keysym = ", $w->XEvent->K, "\n";
#});
###################
# CSV navigation
$mw->bind('<KeyPress-n>' => sub { next_csv(1); });
$mw->bind('<KeyPress-p>' => sub { next_csv(-1); });
$mw->bind('<KeyPress-c>' => sub { new_csv(); });
$mw->bind('<KP_Add>' => sub { new_csv(); });
$mw->bind('<KeyPress-s>' => sub { save_csv(); });
$mw->bind('<KeyPress-h>' => sub { toggle_points(); });
$mw->bind('<KP_Up>' => sub { toggle_points(); });
$mw->bind('<KeyPress-b>' => sub { print "Set Base is no longer needed – Add to Front/Back works on the current CSV\n"; });
$mw->bind('<KeyPress-f>' => sub { start_add_mode('front'); });
$mw->bind('<KeyPress-a>' => sub { start_add_mode('back'); });
$mw->bind('<KeyPress-x>' => sub { clear_base(); });
$mw->bind('<KeyPress-e>' => sub { start_density_edit(); });
###########
#$mw->bind('<Any-KeyPress>' => sub {
#    my $w = shift;
#    print "keysym = ", $w->XEvent->K, "\n";
#+});

##########
# Create the separate controls window. It shares this script's MainLoop.
create_controls($mw);

MainLoop;

###########

sub load_csv {
    $current_file = $csv_files[$csv_index];
    @points = ();
    @spline_preview = ();

    if (open my $fh, '<', $current_file) {
        while (my $line = <$fh>) {
            chomp $line;
            next if $line =~ /^\s*$/;

            my @fields = split /,/, $line, -1;
            next if @fields < 6;
            next if @fields % 2 != 0;

            my %data;
            while (@fields >= 2) {
                my $key = shift @fields;
                my $value = shift @fields;
                $data{$key} = $value;
            }

            next unless defined $data{x} && defined $data{y};
            next unless $data{x} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;
            next unless $data{y} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;

            # CSV stores centre-relative; convert to top-left absolute for display
            my $x_abs = 0 + $data{x} + int($W / 2);
            my $y_abs = 0 + $data{y} + int($H / 2);

            push @points, {
                x => $x_abs,
                y => $y_abs,
 ###########
 
 ###########
                (defined $data{w} && $data{w} =~ /^\s*-?\d+(?:\.\d+)?\s*$/ 
                    ? (w => 0 + $data{w}) : ()),
                (defined $data{h} && $data{h} =~ /^\s*-?\d+(?:\.\d+)?\s*$/ 
                    ? (h => 0 + $data{h}) : ()),
            };
        }
        close $fh;
    }

    load_other_points();
    # Treat loaded points as key points (until a smooth happens)
    @key_points = map { { x => $_->{x}, y => $_->{y} } } @points;
    $has_smoothed = 0;
    draw_points();
    draw_base_overlay();
    update_status();
}


###########
sub reverse_points_if_needed {
    return unless $reverse_on_save && @points > 1;
    @points = reverse @points;
    print "Reversed point order (" . scalar(@points) . " points)\n";
}

sub save_csv {

    if ($merge_mode) {
        commit_add();
        return;
    }

    if (!@points) {
        print "Empty CSV not saved: $current_file\n";
        # Clear base on explicit Save even if empty
        clear_base() if $base_file;
        return;
    }

    reverse_points_if_needed();

    open my $fh, '>', $current_file
        or die "Cannot write $current_file: $!";

    for my $p (@points) {
        # Force integer coordinates when saving
        my $x = int($p->{x} + 0.5);
        my $y = int($p->{y} + 0.5);
        # Save relative to canvas centre (0,0 = middle)
        my $x_centre = $x - int($W / 2);
        my $y_centre = $y - int($H / 2);

        print $fh join(',', 'image', $images[$index], 'x', $x_centre, 'y', $y_centre), "\n";
    }

    close $fh;
    update_status();
    print "Saved $current_file (" . scalar(@points) . " points)\n";

    # Clear base after a normal save
    clear_base() if $base_file;
}

sub next_csv {
    my ($direction) = @_;

    # Do not leave empty CSVs behind
    if (!@points && defined $current_file && -e $current_file) {
        unlink $current_file;
        print "Removed empty $current_file\n";
        clear_base() if $base_file;
    } else {
        save_csv();
    }

    # Refresh list after possible unlink
    @csv_files = sort glob("$save_dir/points_*.csv");
    return unless @csv_files;

    $csv_index += $direction;
    $csv_index = $#csv_files if $csv_index < 0;
    $csv_index = 0         if $csv_index > $#csv_files;

    load_csv();
}





sub new_csv {
    # 1. Commit any pending add-to-front / add-to-back
    if ($merge_mode) {
        commit_add();
    }

    # 2. Save the current CSV if it has points (and clean up empties)
    if (@points) {
        # Temporarily clear mode so save_csv does a normal write
        my $saved_mode = $merge_mode;
        $merge_mode = '';
        save_csv();
        $merge_mode = $saved_mode;
    } else {
        if (defined $current_file && -e $current_file) {
            unlink $current_file;
            print "Removed empty $current_file\n";
        }
    }

    # 3. Clear any internal add-mode state
    clear_base() if $base_file;

    # 4. Create a fresh empty CSV and switch to it
    @csv_files = sort glob("$save_dir/points_*.csv");

    my $next = 1;
    for my $file (@csv_files) {
        if ($file =~ /points_(\d+)\.csv$/) {
            my $number = $1;
            $next = $number + 1 if $number >= $next;
        }
    }

    my $file = sprintf("%s/points_%03d.csv", $save_dir, $next);
    open my $fh, '>', $file or die "Cannot create $file: $!";
    close $fh;

    push @csv_files, $file;
    $csv_index = $#csv_files;

    load_csv();
    print "Created new empty CSV: $file\n";
}


sub add_point {
    my ($c, $x, $y) = @_;

    # Clicking on the canvas should release focus from the num-points entry
    # so subsequent keypad keys are not eaten by the entry.
    $mw->focus if $points_entry;

    @spline_preview = ();   # clear old curve when adding a new point
    push @points, { x => $x, y => $y };

    # Keep key points in sync while still in manual (pre-smooth) mode
    if (!$has_smoothed) {
        @key_points = map { { x => $_->{x}, y => $_->{y} } } @points;
    }

    draw_points();
    update_status();
}

sub delete_last_point {
    return unless @points;
    pop @points;
    @spline_preview = ();
    if (!$has_smoothed) {
        @key_points = map { { x => $_->{x}, y => $_->{y} } } @points;
    }
    draw_points();
    update_status();
    print "Deleted last point\n";
}


sub load_other_points {
    @other_points = ();

    for my $file (@csv_files) {
        next if $file eq $current_file;

        open my $fh, '<', $file or next;

        while (my $line = <$fh>) {
            chomp $line;
            next if $line =~ /^\s*$/;

            my @fields = split /,/, $line, -1;
            next if @fields < 6;
            next if @fields % 2 != 0;

            my %data;
            while (@fields >= 2) {
                my $key = shift @fields;
                my $value = shift @fields;
                $data{$key} = $value;
            }

            next unless defined $data{x} && defined $data{y};
            next unless $data{x} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;
            next unless $data{y} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;

            # CSV stores centre-relative; convert to top-left absolute for display
            my $x_abs = 0 + $data{x} + int($W / 2);
            my $y_abs = 0 + $data{y} + int($H / 2);

            push @other_points, {
                x => $x_abs,
                y => $y_abs,
            };
        }

        close $fh;
    }
}



sub draw_image {
    $photo = $mw->Photo(
        -file => "$img_dir/$images[$index]"
    );

    $canvas->delete('all');

    $canvas->createImage(
        0, 0,
        -image  => $photo,
        -anchor => 'nw',
        -tags   => 'background',
    );

    draw_points();
    draw_base_overlay();
    draw_spline_preview();
    update_status($index) ##----added---#
}


sub draw_points {
    $canvas->delete('current_dots');
    $canvas->delete('other_dots');

    # Other CSV sets: controlled by H
    if ($show_points) {
        for my $p (@other_points) {
            $canvas->createOval(
                $p->{x} - 3, $p->{y} - 3,
                $p->{x} + 3, $p->{y} + 3,
                -fill    => 'blue',
                -outline => 'blue',
                -tags    => 'other_dots',
            );
        }
    }

    # Current CSV set: always visible
    # When in add-to-front/back mode the temporary new points use a distinct colour
    my $draw_colour = $point_colour;
    if ($merge_mode eq 'front') {
        $draw_colour = 'orange';
    } elsif ($merge_mode eq 'back') {
        $draw_colour = 'yellow';
    }

    for my $p (@points) {
        $canvas->createOval(
            $p->{x} - 3, $p->{y} - 3,
            $p->{x} + 3, $p->{y} + 3,
            -fill    => $draw_colour,
            -outline => $draw_colour,
            -tags    => 'current_dots',
        );
    }

    draw_spline_preview();
}

sub draw_spline_preview {
    $canvas->delete('spline_preview');
    return unless @spline_preview >= 2;

    for my $i (1 .. $#spline_preview) {
        my ($p1, $p2) = ($spline_preview[$i-1], $spline_preview[$i]);
        $canvas->createLine(
            $p1->{x}, $p1->{y},
            $p2->{x}, $p2->{y},
            -fill   => '#888888',
            -width  => 1,
            -dash   => '.',
            -tags   => 'spline_preview',
        );
    }
}

sub toggle_points {
    $show_points = !$show_points;
    draw_points();
    update_status();
}


sub update_status2 {
    my ($file_num)= @_; # added 
    $file_num++;
    my $name = $current_file;
    $name =~ s{.*/}{};

    my $base_name = $base_file || '(none)';
    $base_name =~ s{.*/}{};

    my $mode_txt = $merge_mode ? "  [ADDING TO " . uc($merge_mode) . " – draw then S to commit]" : '';

    $status->configure(
        -text => sprintf(
            'CSV %d/%d: %s  Points: %d  BaSe: %s%s Frame: %d', 
            $csv_index + 1,
            scalar(@csv_files),
            $name,
            scalar(@points),
            $base_name,
            $mode_txt,
            scalar $file_num
        )
    );

    my $title = "Point Collector - $name";
    $mw->title($title);
}

sub update_status {
    my ($file_num) = @_;
    $file_num++;                 # make it 1-based

    my $name = $current_file;
    $name =~ s{.*/}{};

    my $mode_txt = $merge_mode
        ? "  [ADDING TO " . uc($merge_mode) . " – draw then S to commit]"
        : '';

    $status->configure(
        -text => sprintf(
            'CSV %d/%d: %s  Points: %d%s Frame: %d',
            $csv_index + 1,
            scalar(@csv_files),
            $name,
            scalar(@points),
            $mode_txt,
            $file_num
        )
    );

    $mw->title("Point Collector - $name");
}

sub set_base {
    if ($merge_mode) {
        print "Finish or cancel the current add-to mode first\n";
        return;
    }
    save_csv();

    $base_file = $current_file;
    draw_base_overlay();
    update_status();
    print "Base CSV set to $base_file\n";
}


sub start_add_mode {
    my ($where) = @_;

    if ($merge_mode) {
        print "Already in add mode – press S to commit or X to cancel\n";
        return;
    }

    unless ($current_file && -e $current_file) {
        print "No current CSV to add to\n";
        return;
    }

    # If we have saved key points (pre-smooth / pre-density), restore them first
    # so add-to-front/rear works on the original manual points, not the dense ones.
    if (@key_points) {
        @points = map { { x => $_->{x}, y => $_->{y} } } @key_points;
        @spline_preview = ();
        print "Restored original key points (" . scalar(@points) . ") for add mode\n";
    }

    # Save current points so the overlay can show them, then treat current as the target
    save_csv() if @points;
    $base_file = $current_file;

    $merge_mode = $where;
    $point_colour = ($where eq 'front') ? 'orange' : 'yellow';
    @points = ();
    @spline_preview = ();
    draw_points();
    draw_base_overlay();
    update_status();
    print "Adding to $where of current CSV (original stays red, new dots in $point_colour) – draw then press S to commit\n";
}


sub commit_add {
    return unless $merge_mode;
    return unless $base_file && -e $base_file;

    if (!@points) {
        print "No new points to add – mode cancelled\n";
        $merge_mode = '';
        update_status();
        return;
    }

    # Load existing base points (absolute coords)
    my @base_pts;
    if (open my $fh, '<', $base_file) {
        while (my $line = <$fh>) {
            chomp $line;
            next if $line =~ /^\s*$/;
            my @fields = split /,/, $line, -1;
            next if @fields < 6 || @fields % 2 != 0;
            my %data;
            while (@fields >= 2) {
                my $k = shift @fields;
                my $v = shift @fields;
                $data{$k} = $v;
            }
            next unless defined $data{x} && defined $data{y};
            next unless $data{x} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;
            next unless $data{y} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;
            push @base_pts, {
                x => 0 + $data{x} + int($W / 2),
                y => 0 + $data{y} + int($H / 2),
            };
        }
        close $fh;
    }

    # Reverse new points for front so the first drawn is adjacent to old start
    if ($merge_mode eq 'front') {
        @points = reverse @points;
    }

    # Combine
    if ($merge_mode eq 'front') {
        @points = (@points, @base_pts);
    } else {
        @points = (@base_pts, @points);
    }

    # Write combined points to the base file (overwrite)
    open my $out, '>', $base_file
        or die "Cannot write $base_file: $!";
    for my $p (@points) {
        my $x = int($p->{x} + 0.5);
        my $y = int($p->{y} + 0.5);
        my $x_centre = $x - int($W / 2);
        my $y_centre = $y - int($H / 2);
        print $out join(',', 'image', $images[$index], 'x', $x_centre, 'y', $y_centre), "\n";
    }
    close $out;

    print "Committed $merge_mode add: " . scalar(@points) . " points now in $base_file\n";

    $merge_mode = '';
    $point_colour = 'red';

    # Switch to the updated base as current
    @csv_files = sort glob("$save_dir/points_*.csv");
    for my $i (0 .. $#csv_files) {
        if ($csv_files[$i] eq $base_file) {
            $csv_index = $i;
            last;
        }
    }
    load_csv();

    # Clear base after committing the add
    clear_base();
}


# Old file-based merge kept for reference but no longer used
sub merge_csv {
    my ($where) = @_;
    print "merge_csv is deprecated – use Add to Front/Back then S to commit\n";
}
################

sub draw_base_overlay {
    $canvas->delete('base_overlay');

    return unless defined $base_file && $base_file ne '';
    return unless -e $base_file;

    open my $fh, '<', $base_file or return;

    while (my $line = <$fh>) {
        chomp $line;
        next if $line =~ /^\s*$/;

        my @fields = split /,/, $line, -1;
        next if @fields < 6;
        next if @fields % 2 != 0;

        my %data;
        while (@fields >= 2) {
            my $key = shift @fields;
            my $value = shift @fields;
            $data{$key} = $value;
        }

        next unless defined $data{x} && defined $data{y};
        next unless $data{x} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;
        next unless $data{y} =~ /^\s*-?\d+(?:\.\d+)?\s*$/;

        # CSV stores centre-relative; convert to top-left absolute for display
        my $x_abs = 0 + $data{x} + int($W / 2);
        my $y_abs = 0 + $data{y} + int($H / 2);

        $canvas->createOval(
            $x_abs - 3, $y_abs - 3,
            $x_abs + 3, $y_abs + 3,
            -fill    => 'red',
            -outline => 'red',
            -tags    => 'base_overlay',
        );
    }

    close $fh;
}




sub clear_base {
    $base_file = '';
    $merge_mode = '';
    $point_colour = 'red';
    $canvas->delete('base_overlay');
    draw_points();
    update_status();
    print "Base CSV cleared (any add mode cancelled)\n";
}	
	



# ------------------------------------------------------------
# Point Controls menu
# ------------------------------------------------------------

sub create_controls {
    my ($parent) = @_;

    my $controls = $parent->Toplevel;
    $controls->title('Point Controls');
    $controls->resizable(0, 0);
    $controls->attributes(-topmost => 1);

    my @buttons = (
        ['C - Create New CSV',       'c'],
        ['S - Save Current CSV',     's'],
        ['N - Next CSV',             'n'],
        ['P - Previous CSV',         'p'],
        ['F - Add to Front of Current', 'f'],
        ['A - Add to Back of Current',  'a'],
        ['X - Cancel Add Mode',      'x'],
        ['H - Hide/Show Other Dots', 'h'],
        ['< - Previous Image',       'Left'],
        ['> - Next Image',           'Right'],
    );

    my $row = 0;

    for my $item (@buttons) {
        my ($label, $key) = @$item;

        my $colour = 'lightgrey';
        if ($key =~ /^[fax]$/) {
            $colour = 'yellow';
        }

        $controls->Button(
            -text       => $label,
            -font       => ['Helvetica', 12],
            -width      => 24,
            -height     => 1,
            -command    => sub { send_key($key); },
            -background => $colour,
        )->grid(
            -row    => $row++,
            -column => 0,
            -padx   => 6,
            -pady   => 2,
            -sticky => 'ew',
        );
    }

    # --- Reverse on Save/New toggle ---
    my $reverse_btn;
    $reverse_btn = $controls->Button(
        -text       => 'Reverse on Save/New: OFF',
        -font       => ['Helvetica', 12],
        -width      => 24,
        -background => 'lightgrey',
        -command    => sub {
            $reverse_on_save = !$reverse_on_save;
            if ($reverse_on_save) {
                $reverse_btn->configure(
                    -text => 'Reverse on Save/New: ON',
                    -background => 'orange',
                );
            } else {
                $reverse_btn->configure(
                    -text => 'Reverse on Save/New: OFF',
                    -background => 'lightgrey',
                );
            }
        },
    )->grid(
        -row    => $row++,
        -column => 0,
        -padx   => 6,
        -pady   => 2,
        -sticky => 'ew',
    );

    # --- Smooth Line controls ---
    $controls->Label(
        -text => 'Smooth points:',
        -font => ['Helvetica', 12],
    )->grid(
        -row    => $row,
        -column => 0,
        -sticky => 'w',
        -padx   => 6,
        -pady   => 4,
    );
    $row++;

    my $smooth_frame = $controls->Frame()->grid(
        -row    => $row++,
        -column => 0,
        -sticky => 'ew',
        -padx   => 6,
    );

    $smooth_frame->Label(
        -text => 'Num:',
        -font => ['Helvetica', 11],
    )->pack(-side => 'left');

$points_entry = $smooth_frame->Entry(
    -textvariable    => \$num_points,
    -width           => 5,
    -font            => ['Helvetica', 11],
    -validate        => 'key',
    -validatecommand => [sub {
        my $proposed = shift;
        my $ok = ($proposed eq '' || $proposed =~ /^\d+$/);
        # only turn white when the proposed value is acceptable
        $points_entry->configure(-background => 'white') if $ok && $points_entry;
        return $ok;
    }, '%P'],
    -invalidcommand  => sub {
        # illegal keystroke → pure red
        $points_entry->configure(-background => '#ff5555') if $points_entry;
    },
)->pack(-side => 'left', -padx => 4);

# delete the old <KeyRelease> binding completely – it is no longer needed

    $smooth_frame->Button(
        -text       => 'Smooth Line',
        -font       => ['Helvetica', 12],
        -background => 'cyan',
        -command    => \&smooth_current_line,
    )->pack(-side => 'left', -padx => 4);

    $controls->Button(
        -text       => 'Undo Smooth',
        -font       => ['Helvetica', 12],
        -width      => 24,
        -background => 'orange',
        -command    => \&undo_smooth,
    )->grid(
        -row    => $row++,
        -column => 0,
        -padx   => 6,
        -pady   => 2,
        -sticky => 'ew',
    );

    $controls->Button(
        -text       => 'E - Edit Density in Selection',
        -font       => ['Helvetica', 12],
        -width      => 24,
        -background => 'lightgreen',
        -command    => \&start_density_edit,
    )->grid(
        -row    => $row++,
        -column => 0,
        -padx   => 6,
        -pady   => 2,
        -sticky => 'ew',
    );

    $controls->Button(
        -text       => 'Delete Last Point',
        -font       => ['Helvetica', 12],
        -width      => 24,
        -background => 'pink',
        -command    => \&delete_last_point,
    )->grid(
        -row    => $row++,
        -column => 0,
        -padx   => 6,
        -pady   => 2,
        -sticky => 'ew',
    );

    my @cursors = (
        ['Black Cursor', 'black'],
        ['White Cursor', 'white'],
        ['Green Cursor', 'green'],
    );

    for my $item (@cursors) {
        my ($label, $colour) = @$item;
        my $text_colour = ($colour eq 'black') ? 'white' : 'black';

        $controls->Button(
            -text       => $label,
            -font       => ['Helvetica', 12],
            -width      => 24,
            -height     => 1,
            -background => $colour,
            -foreground => $text_colour,
            -command    => sub {
                system('xsetroot', '-xcf',
                    "$ENV{HOME}/pointers/$colour", '9');
            },
        )->grid(
            -row    => $row++,
            -column => 0,
            -padx   => 6,
            -pady   => 2,
            -sticky => 'ew',
        );
    }

    $controls->Button(
        -text       => 'Arrow',
        -font       => ['Helvetica', 12],
        -width      => 24,
        -height     => 1,
        -command    => sub {
            system('xsetroot', '-cursor_name', 'left_ptr');
        },
    )->grid(
        -row    => $row++,
        -column => 0,
        -padx   => 6,
        -pady   => 2,
        -sticky => 'ew',
    );

    $controls->Button(
        -text       => 'Crosshair',
        -font       => ['Helvetica', 12],
        -width      => 24,
        -height     => 1,
        -command    => sub {
            system('xsetroot', '-cursor_name', 'crosshair');
        },
    )->grid(
        -row    => $row++,
        -column => 0,
        -padx   => 6,
        -pady   => 2,
        -sticky   => 'ew',
    );

    # Quit button for the controls/menu window
    $controls->Button(
        -text       => 'QUIT',
        -font       => ['Helvetica', 12],
        -width      => 24,
        -height     => 1,
        -background => 'red',
        -foreground => 'white',
        -command    => sub { $mw->destroy; },
    )->grid(
        -row    => $row++,
        -column => 0,
        -padx   => 6,
        -pady   => 4,
        -sticky => 'ew',
    );

    # Clicking anywhere in the controls window (except the entry itself)
    # should release focus from the num-points entry.
    $controls->bind('<Button-1>', sub {
        my $ev = $_[0]->XEvent;
        my $w  = $ev->W;
        $mw->focus if $points_entry && $w != $points_entry;
    });
}


sub send_key {
    my ($key) = @_;

    # Any controls button should release focus from the entry
    $mw->focus if $points_entry;

    my @windows = `xdotool search --onlyvisible --name 'Point Collector'`;
    chomp @windows;

    if (!@windows) {
        warn "Point Collector window not found\n";
        return;
    }

    my $window = $windows[-1];

    system('xdotool', 'windowactivate', '--sync', $window);
    system('xdotool', 'key', '--clearmodifiers', $key);
}

# ----------------------------------------------------------
# Smooth line: Catmull-Rom spline + even resampling
# ----------------------------------------------------------

sub smooth_current_line {
    # Smooth button click should also release focus from the entry
    $mw->focus if $points_entry;

    return unless @points >= 2;

    # Refuse to run unless num_points is a positive integer >= 2
    unless (defined $num_points && $num_points =~ /^\d+$/ && $num_points >= 2) {
        $points_entry->configure(-background => '#ff5555') if $points_entry;
        $points_entry->focus if $points_entry;
        print "Num points must be an integer >= 2\n";
        return;
    }

    # Good value → make sure the box is normal colour
    $points_entry->configure(-background => 'white') if $points_entry;

    # Backup current points for Undo
    @points_before_smooth = map {
        { x => $_->{x}, y => $_->{y} }
    } @points;

    # Also keep as key points (original manual / pre-density) for later front/rear adds
    @key_points = map { { x => $_->{x}, y => $_->{y} } } @points;
    $has_smoothed = 1;

    # Build spline
    my $spline_ref = spline_points(\@points, $smooth_res);
    @spline_preview = @$spline_ref;

    return unless @spline_preview >= 2;

    # Compute total length
    my $total_length = 0;
    for my $i (1 .. $#spline_preview) {
        my $dx = $spline_preview[$i]{x} - $spline_preview[$i-1]{x};
        my $dy = $spline_preview[$i]{y} - $spline_preview[$i-1]{y};
        $total_length += sqrt($dx*$dx + $dy*$dy);
    }

    my $spacing = $total_length / ($num_points - 1);
    my @resampled = generate_even_points(\@spline_preview, $spacing);

    # Replace current points with evenly spaced ones
    @points = map { { x => $_->{x}, y => $_->{y} } } @resampled;

    draw_points();
    update_status();
    print "Smoothed to $num_points evenly spaced points\n";
}

sub undo_smooth {
    return unless @points_before_smooth;

    @points = map {
        { x => $_->{x}, y => $_->{y} }
    } @points_before_smooth;

    @points_before_smooth = ();
    @spline_preview = ();
    $has_smoothed = 0;
    @key_points = map { { x => $_->{x}, y => $_->{y} } } @points;

    draw_points();
    update_status();
    print "Undid last smooth\n";
}

# Catmull-Rom spline (from the curve editor)
sub spline_points {
    my ($pts_ref, $res) = @_;
    my @pts = @$pts_ref;
    return [] unless @pts >= 2;

    my @spline;
    my @tmp = ($pts[0], @pts, $pts[-1]);

    for my $i (0 .. $#tmp - 3) {
        my ($p0, $p1, $p2, $p3) = @tmp[$i .. $i+3];
        for my $j (0 .. $res - 1) {
            my $t  = $j / $res;
            my $t2 = $t * $t;
            my $t3 = $t2 * $t;

            my $x = 0.5 * (
                (2 * $p1->{x}) +
                (-$p0->{x} + $p2->{x}) * $t +
                (2 * $p0->{x} - 5 * $p1->{x} + 4 * $p2->{x} - $p3->{x}) * $t2 +
                (-$p0->{x} + 3 * $p1->{x} - 3 * $p2->{x} + $p3->{x}) * $t3
            );

            my $y = 0.5 * (
                (2 * $p1->{y}) +
                (-$p0->{y} + $p2->{y}) * $t +
                (2 * $p0->{y} - 5 * $p1->{y} + 4 * $p2->{y} - $p3->{y}) * $t2 +
                (-$p0->{y} + 3 * $p1->{y} - 3 * $p2->{y} + $p3->{y}) * $t3
            );

            push @spline, { x => $x, y => $y };
        }
    }
    push @spline, $pts[-1];
    return \@spline;
}

# Evenly space points along the spline
sub generate_even_points {
    my ($pts_ref, $spacing) = @_;
    my @pts = @$pts_ref;
    return () unless @pts >= 2;

    my @result;
    my @cum_length = (0);

    for my $i (1 .. $#pts) {
        my $dx = $pts[$i]{x} - $pts[$i-1]{x};
        my $dy = $pts[$i]{y} - $pts[$i-1]{y};
        push @cum_length, $cum_length[-1] + sqrt($dx*$dx + $dy*$dy);
    }

    my $total_length = $cum_length[-1];
    my $d = 0;
    my $seg_idx = 0;

    while ($d <= $total_length) {
        while ($seg_idx < $#pts && $cum_length[$seg_idx + 1] < $d) {
            $seg_idx++;
        }
        my $seg_len = $cum_length[$seg_idx + 1] - $cum_length[$seg_idx];
        my $t = ($seg_len > 0) ? ($d - $cum_length[$seg_idx]) / $seg_len : 0;

        my $x = $pts[$seg_idx]{x} + $t * ($pts[$seg_idx + 1]{x} - $pts[$seg_idx]{x});
        my $y = $pts[$seg_idx]{y} + $t * ($pts[$seg_idx + 1]{y} - $pts[$seg_idx]{y});

        push @result, { x => $x, y => $y };
        $d += $spacing;
    }

    push @result, $pts[-1];
    return @result;
}

# ------------------------------------------------------------

# ------------------------------------------------------------
# Density edit in a selected section (movable rect + live preview)
# ------------------------------------------------------------

my $density_dialog;          # the open dialog window
my $preview_active = 0;
my @points_backup;           # original points while previewing
my $density_factor_var = 0;   # slider value, zero in the middle

sub start_density_edit {
    return unless @points >= 3;
    if ($merge_mode) {
        print "Finish or cancel add mode first\n";
        return;
    }
    if ($density_mode) {
        print "Already in density edit mode\n";
        return;
    }

    $density_mode = 1;
    $preview_active = 0;

    # Disable normal point-adding while in edit mode
    $canvas->CanvasBind('<Button-1>' => [ \&density_canvas_click, Ev('x'), Ev('y') ]);
    $canvas->CanvasBind('<B1-Motion>' => '');
    $canvas->CanvasBind('<ButtonRelease-1>' => '');

    print "Density edit mode: drag to create a selection rectangle.\n";
    print "Once created you can drag the rectangle to move it, or drag near edges to resize.\n";
    print "Clicks elsewhere are ignored. Press Escape or Cancel to exit.\n";

    # Escape cancels
    $mw->bind('<Escape>' => \&cancel_density_edit);
}

sub density_canvas_click {
    my ($c, $x, $y) = @_;
    # If we already have a rectangle, ignore plain clicks (move/resize handled by item binds)
    return if $sel_rect;

    # Start a new rectangle
    $sel_x1 = $x;
    $sel_y1 = $y;
    $sel_x2 = $x;
    $sel_y2 = $y;

    $canvas->delete('sel_rect');
    $sel_rect = $canvas->createRectangle(
        $x, $y, $x, $y,
        -outline => 'cyan',
        -width   => 2,
        -dash    => '-',
        -tags    => 'sel_rect',
    );

    # Bind drag for initial creation
    $canvas->CanvasBind('<B1-Motion>' => [ \&density_create_drag, Ev('x'), Ev('y') ]);
    $canvas->CanvasBind('<ButtonRelease-1>' => [ \&density_create_end, Ev('x'), Ev('y') ]);
}

sub density_create_drag {
    my ($c, $x, $y) = @_;
    return unless $sel_rect;
    $sel_x2 = $x;
    $sel_y2 = $y;
    $canvas->coords($sel_rect, $sel_x1, $sel_y1, $x, $y);
}

sub density_create_end {
    my ($c, $x, $y) = @_;
    $sel_x2 = $x;
    $sel_y2 = $y;

    # Stop the create-drag bindings
    $canvas->CanvasBind('<B1-Motion>' => '');
    $canvas->CanvasBind('<ButtonRelease-1>' => '');

    # Normalise
    my ($rx1, $ry1, $rx2, $ry2) = normalise_rect($sel_x1, $sel_y1, $sel_x2, $sel_y2);
    $canvas->coords($sel_rect, $rx1, $ry1, $rx2, $ry2);
    ($sel_x1, $sel_y1, $sel_x2, $sel_y2) = ($rx1, $ry1, $rx2, $ry2);

    # Now make the rectangle movable / resizable via item bindings
    setup_rect_interaction();

    # Open the density dialog
    open_density_dialog();
}

sub normalise_rect {
    my ($x1, $y1, $x2, $y2) = @_;
    return (
        $x1 < $x2 ? $x1 : $x2,
        $y1 < $y2 ? $y1 : $y2,
        $x1 > $x2 ? $x1 : $x2,
        $y1 > $y2 ? $y1 : $y2,
    );
}

sub setup_rect_interaction {
    return unless $sel_rect;

    # Bind to the rectangle item itself
    $canvas->bind($sel_rect, '<Button-1>' => [ \&rect_press, Ev('x'), Ev('y') ]);
    $canvas->bind($sel_rect, '<B1-Motion>' => [ \&rect_motion, Ev('x'), Ev('y') ]);
    $canvas->bind($sel_rect, '<ButtonRelease-1>' => \&rect_release);

    # Raise it so it receives events
    $canvas->raise($sel_rect);
}

my ($drag_mode, $drag_dx, $drag_dy, $orig_coords);

sub rect_press {
    my ($item, $x, $y) = @_;
    my @c = $canvas->coords($sel_rect);
    $orig_coords = \@c;

    # Detect if near an edge/corner (within 8 px) → resize, else move
    my $margin = 8;
    my ($x1, $y1, $x2, $y2) = @c;
    my $on_left   = abs($x - $x1) < $margin;
    my $on_right  = abs($x - $x2) < $margin;
    my $on_top    = abs($y - $y1) < $margin;
    my $on_bottom = abs($y - $y2) < $margin;

    if ($on_left || $on_right || $on_top || $on_bottom) {
        $drag_mode = 'resize';
        # store which edges
        $drag_dx = ($on_left ? 'l' : $on_right ? 'r' : '') .
                   ($on_top ? 't' : $on_bottom ? 'b' : '');
    } else {
        $drag_mode = 'move';
        $drag_dx = $x - $x1;
        $drag_dy = $y - $y1;
    }
}

sub rect_motion {
    my ($item, $x, $y) = @_;
    return unless $drag_mode && $orig_coords;

    my ($x1, $y1, $x2, $y2) = @$orig_coords;

    if ($drag_mode eq 'move') {
        my $w = $x2 - $x1;
        my $h = $y2 - $y1;
        my $nx1 = $x - $drag_dx;
        my $ny1 = $y - $drag_dy;
        $canvas->coords($sel_rect, $nx1, $ny1, $nx1 + $w, $ny1 + $h);
    } elsif ($drag_mode eq 'resize') {
        my $nx1 = $x1; my $ny1 = $y1; my $nx2 = $x2; my $ny2 = $y2;
        $nx1 = $x if $drag_dx =~ /l/;
        $nx2 = $x if $drag_dx =~ /r/;
        $ny1 = $y if $drag_dx =~ /t/;
        $ny2 = $y if $drag_dx =~ /b/;
        # keep minimum size
        if (abs($nx2 - $nx1) > 10 && abs($ny2 - $ny1) > 10) {
            $canvas->coords($sel_rect, $nx1, $ny1, $nx2, $ny2);
        }
    }
}

sub rect_release {
    $drag_mode = undef;
    # Update stored coords
    my @c = $canvas->coords($sel_rect);
    ($sel_x1, $sel_y1, $sel_x2, $sel_y2) = normalise_rect(@c);
    $canvas->coords($sel_rect, $sel_x1, $sel_y1, $sel_x2, $sel_y2);

    # Refresh preview if dialog is open
    refresh_preview() if $density_dialog && Tk::Exists($density_dialog);
}

sub open_density_dialog {
    return if $density_dialog && $density_dialog->Exists;

    $density_factor_var = 0;   # start at zero

    $density_dialog = $mw->Toplevel;
    $density_dialog->title('Edit density');
    $density_dialog->resizable(0, 0);
    $density_dialog->attributes(-topmost => 1);

    $density_dialog->Label(
        -text => "Drag the slider to change density\n" .
                 "Left / negative = fewer dots (sparser in middle)\n" .
                 "Right / positive = more dots (denser in middle)\n" .
                 "Zero = no change. Preview updates live.",
        -font => ['Helvetica', 11],
        -justify => 'left',
    )->pack(-padx => 12, -pady => 8);

    my $scale = $density_dialog->Scale(
        -from        => -1.5,
        -to          =>  1.5,
        -resolution  =>  0.1,
        -orient      => 'horizontal',
        -length      => 280,
        -variable    => \$density_factor_var,
        -command     => sub { refresh_preview(); },
        -label       => 'Density factor',
        -font        => ['Helvetica', 11],
    )->pack(-padx => 12, -pady => 6);

    # Show numeric value under the slider
    my $val_label = $density_dialog->Label(
        -textvariable => \$density_factor_var,
        -font => ['Helvetica', 14, 'bold'],
    )->pack(-pady => 2);

    my $btn_frame = $density_dialog->Frame->pack(-pady => 8);
    $btn_frame->Button(
        -text => 'Apply',
        -font => ['Helvetica', 12],
        -background => 'lightgreen',
        -command => \&apply_density_from_dialog,
    )->pack(-side => 'left', -padx => 8);

    $btn_frame->Button(
        -text => 'Cancel',
        -font => ['Helvetica', 12],
        -command => \&cancel_density_edit,
    )->pack(-side => 'left', -padx => 8);

    # Initial preview
    refresh_preview();

    $density_dialog->protocol('WM_DELETE_WINDOW' => \&cancel_density_edit);
}

sub refresh_preview {
    return unless $sel_rect && $density_dialog;

    my $factor = $density_factor_var;
    $factor = 0 unless defined $factor && $factor =~ /^-?\d+(?:\.\d+)?$/;
    $factor = 0 + $factor;

    # Find current selection range
    my ($start, $end) = find_selected_range();
    if (!defined $start || $end <= $start) {
        # nothing selectable – restore if we were previewing
        restore_from_backup() if $preview_active;
        return;
    }

    # Backup original points the first time we preview
    if (!$preview_active) {
        @points_backup = map { { x => $_->{x}, y => $_->{y} } } @points;
        $preview_active = 1;
    } else {
        # restore from backup before applying new preview
        @points = map { { x => $_->{x}, y => $_->{y} } } @points_backup;
    }

    # Compute and temporarily install the new section
    my $ok = compute_and_splice_density($start, $end, $factor, 1);  # 1 = preview
    draw_points();
    # re-raise rectangle so it stays on top
    $canvas->raise($sel_rect) if $sel_rect;
}

sub find_selected_range {
    return (-1, -1) unless $sel_rect;
    my ($rx1, $ry1, $rx2, $ry2) = $canvas->coords($sel_rect);
    ($rx1, $ry1, $rx2, $ry2) = normalise_rect($rx1, $ry1, $rx2, $ry2);

    # Always search the original (backup) points when a preview is active,
    # otherwise the changing point count would shift indices.
    my $src = ($preview_active && @points_backup) ? \@points_backup : \@points;

    my ($start_idx, $end_idx) = (-1, -1);
    for my $i (0 .. $#$src) {
        my $p = $src->[$i];
        if ($p->{x} >= $rx1 && $p->{x} <= $rx2 &&
            $p->{y} >= $ry1 && $p->{y} <= $ry2) {
            $start_idx = $i if $start_idx < 0;
            $end_idx = $i;
        } elsif ($start_idx >= 0) {
            last;
        }
    }
    return ($start_idx, $end_idx);
}

sub compute_and_splice_density {
    my ($start, $end, $factor, $is_preview) = @_;
    return 0 if $end <= $start;
    return 0 if abs($factor) < 0.001 && !$is_preview;

    my @prefix  = @points[0 .. $start - 1];
    my @section = @points[$start .. $end];
    my @suffix  = @points[$end + 1 .. $#points];

    my $orig_count = scalar @section;
    my $target = int($orig_count * (1 + $factor) + 0.5);
    $target = 2 if $target < 2;

    my $spline_ref = spline_points(\@section, $smooth_res);
    my @spline = @$spline_ref;
    return 0 unless @spline >= 2;

    my @cum = (0);
    for my $i (1 .. $#spline) {
        my $dx = $spline[$i]{x} - $spline[$i-1]{x};
        my $dy = $spline[$i]{y} - $spline[$i-1]{y};
        push @cum, $cum[-1] + sqrt($dx*$dx + $dy*$dy);
    }
    my $L = $cum[-1];
    return 0 if $L < 1;

    my @new_section;
    if ($target == 2) {
        @new_section = (
            { x => $section[0]{x}, y => $section[0]{y} },
            { x => $section[-1]{x}, y => $section[-1]{y} },
        );
    } else {
        my $steps = 200;
        my @dens_cum = (0);
        for my $k (1 .. $steps) {
            my $t = $k / $steps;
            my $dens = 1 + $factor * 4 * $t * (1 - $t);
            $dens = 0.15 if $dens < 0.15;
            push @dens_cum, $dens_cum[-1] + $dens;
        }
        my $dens_total = $dens_cum[-1];

        for my $i (0 .. $target - 1) {
            my $frac = $i / ($target - 1);
            my $target_dens = $frac * $dens_total;
            my $k = 0;
            $k++ while $k < $steps && $dens_cum[$k] < $target_dens;
            my $t = $k / $steps;
            my $s = $t * $L;

            my $seg = 0;
            $seg++ while $seg < $#spline && $cum[$seg + 1] < $s;
            my $seg_len = $cum[$seg + 1] - $cum[$seg];
            my $u = ($seg_len > 0) ? ($s - $cum[$seg]) / $seg_len : 0;
            my $x = $spline[$seg]{x} + $u * ($spline[$seg + 1]{x} - $spline[$seg]{x});
            my $y = $spline[$seg]{y} + $u * ($spline[$seg + 1]{y} - $spline[$seg]{y});
            push @new_section, { x => $x, y => $y };
        }
        $new_section[0]  = { x => $section[0]{x},  y => $section[0]{y} };
        $new_section[-1] = { x => $section[-1]{x}, y => $section[-1]{y} };
    }

    @points = (@prefix, @new_section, @suffix);
    return 1;
}

sub apply_density_from_dialog {
    # The preview is already in @points; just make it permanent
    $preview_active = 0;
    @points_backup = ();
    print "Density edit applied.\n";
    exit_density_mode(1);   # 1 = keep changes
}

sub cancel_density_edit {
    restore_from_backup() if $preview_active;
    exit_density_mode(0);
}

sub restore_from_backup {
    return unless $preview_active && @points_backup;
    @points = map { { x => $_->{x}, y => $_->{y} } } @points_backup;
    $preview_active = 0;
    @points_backup = ();
    draw_points();
}

sub exit_density_mode {
    my ($applied) = @_;

    # Restore normal canvas bindings
    $canvas->CanvasBind('<Button-1>' => [ \&add_point, Ev('x'), Ev('y') ]);
    $canvas->CanvasBind('<B1-Motion>' => '');
    $canvas->CanvasBind('<ButtonRelease-1>' => '');

    $canvas->delete('sel_rect');
    $sel_rect = undef;
    $density_mode = 0;
    $preview_active = 0;

    if ($density_dialog && $density_dialog->Exists) {
        $density_dialog->destroy;
    }
    $density_dialog = undef;

    $mw->bind('<Escape>' => '');   # remove escape binding

    draw_points();
    update_status();
    print $applied ? "Density changes kept.\n" : "Density edit cancelled.\n";
}

