#!/usr/bin/perl
# List tool: extract / combine image, w/h, x/y CSV lists
use strict;
use warnings;
use Tk;
use File::Spec;
use File::Copy;
use Image::Size qw(imgsize);
use Text::CSV;
use File::Path qw(make_path);
use feature 'say';
use File::Basename qw(fileparse);
my @dir_stack = ('.');  # Stack to store directories navigated
my ($selected_file,$selected_dir,@contents,$print_dir,@files,$text,$dir,$blank,$img,$img_dir,$xy_file_dir);
my $random_files=2;
#my $image_frames=100;
my $ran_frac=4;
my $c=0;
#my $start_w=100;
my $new_prefix="";
my $new_w=400;
my $new_h;
my $new_x;
my $new_y;
my $frames=50;
my $start_fr=10;
my ($image_width,$image_height,$image_file,$image2_file,$xy_file,$wh_file,$aspect);
my $new_suffix="";
my $save_directory="TEST";
my $change="";
my @keys_list=qw(image wh xy);
my $key="image";
my $static_x=0;
my $static_y=0;
my $dupes =2;
my ($offset_x,$offset_y)=(0,0);
my $canvas_w = 1920;
my $canvas_h = 1080;
# Scale coordinates for resized image
my $old_w = 1920;
my $old_h = 1080;
my $new_w_scale = 960;
my $new_h_scale = 540;
my $scale_csv_file = '';
my $scale_mode = 'file';   # 'file' or 'dir'
#my $doubles=2;
#my $show_all = 1;  # default: show only selected suffixes
my $show_all = 0;   # 0 = filtered extensions only, 1 = all files
my $mw = MainWindow->new;
$mw->title("MAKE LISTS + Coord Converter\n"); 
$mw->geometry("1300x1300+1100+500");
my $frame = $mw->Frame()->grid(qw/ -row 2 -column 0  -sticky w/); 
my $frame3 = $mw->Frame()->grid(qw/ -row 2 -column 1 -rowspan 2  -sticky w/); 
my $frame2=$mw->Frame()->grid(qw/ -row 3 -column 0 -sticky w/);
my $label=$mw->Label(-font => '{Helvetica} 15', -text => "adds to or merges .csv files in directories:", -width=>34, )->grid(qw/ -row 0 -column 1 -columnspan 3 -sticky n/ );
$label=$mw->Label(-font => '{Helvetica} 15', -text => "save directory:", -width=>20)->grid(qw/ -row 0 -column 0 -sticky w/);
my $entry =$mw->Entry(-font => '{Helvetica} 15', -textvariable => \$save_directory, -width=>18)->grid(qw/ -row 0 -column 0  -sticky e/);

my $listbox = $frame->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width=>30)->grid(qw/ -row 0 -column 0 -sticky w/);
my $listbox2 = $frame2->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width=>30, -height =>6)->grid(qw/ -row 0 -column 0  -sticky w/); 
$listbox->bind('<Double-Button-1>', \&select_item);
# blank separator
$frame3->Label(-text => ' ', -font => '{Helvetica} 6')->grid(qw/ -row 14 -column 0 -sticky w/);

my $button = $frame3->Button(-font => '{Helvetica} 15', -text => 'list from all images in dir:', -justify =>'left', -width=>25, -command => sub{&make_csv()})->grid(qw/ -row 16 -column 0 -sticky n/);
##

##
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'add x,y to file:', -justify =>'left', -width=>25, -command => sub{&add_xy()})->grid(qw/ -row 20 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'image,wh file', -width=>10, -command => sub{$image_file=$selected_file;&speak();})->grid(qw/ -row 20 -column 1 -columnspan 2 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'x,y file', -width=>10, -command => sub{$xy_file=$selected_file;&speak();})->grid(qw/ -row 20 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'add w,h to file:', -justify =>'left', -width=>25, -command => sub{&add_wh()})->grid(qw/ -row 22 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'image,x,y file', -width=>10, -command => sub{$image_file=$selected_file;&speak();})->grid(qw/ -row 22 -column 1 -columnspan 2 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'w,h file', -width=>10, -command => sub{$wh_file=$selected_file;&speak();})->grid(qw/ -row 22 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'add images to file:', -justify =>'left', -width=>25, -command => sub{&add_image()})->grid(qw/ -row 24 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'xy,wh file', -width=>10, -command => sub{$xy_file=$selected_file;&speak();})->grid(qw/ -row 24 -column 1 -columnspan 2 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'image file', -width=>10, -command => sub{$image_file=$selected_file;&speak();})->grid(qw/ -row 24 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'add wh of images in file:', -justify =>'left', -width=>25, -command => sub{&add_self_wh()})->grid(qw/ -row 25 -column 0 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'fixed x,y to file', -justify =>'left', -width=>25, -command => sub{&static_xy})->grid(qw/ -row 26 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$static_x, -width=>12)->grid(qw/ -row 26 -column 1 -columnspan 2 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$static_y, -width=>12)->grid(qw/ -row 26 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'add offset x,y', -justify =>'left', -width=>25, -command => sub{&add_offset})->grid(qw/ -row 27 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$offset_x, -width=>12)->grid(qw/ -row 27 -column 1 -columnspan 2 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$offset_y, -width=>12)->grid(qw/ -row 27 -column 3 -columnspan 2 -sticky w/);

# blank separator
$frame3->Label(-text => ' ', -font => '{Helvetica} 6')->grid(qw/ -row 28 -column 0 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'change suffix of all files in dir', -justify =>'left', -width=>25, -command => sub{&change_suffix()})->grid(qw/ -row 29 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_suffix, -width=>28)->grid(qw/ -row 29 -column 1 -columnspan 3 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'change file path in csvs', -justify =>'left', -width=>25, -command => sub{&rewrite_paths($selected_dir, $new_prefix)})->grid(qw/ -row 30 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_prefix, -width=>28)->grid(qw/ -row 30 -column 1 -columnspan 3 -sticky w/);


$button = $frame3->Button(
    -font => '{Helvetica} 15',
    -text => 'clean numbers in names',
    -justify => 'left',
    -width => 25,
    -command => \&clean_numbers_in_names
)->grid(qw/ -row 31 -column 0 -sticky w/);
$frame3->Label(
    -font => '{Helvetica} 11',
    -text => 'e.g. trees-02-list-004.png to trees-list-004.png',
    -justify => 'left',
)->grid(qw/ -row 31 -column 1 -columnspan 3 -sticky w/);


$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'extract from file', -justify =>'left', -width=>25, -command => sub{&extract})->grid(qw/ -row 32 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$key, -width=>12)->grid(qw/ -row 32 -column 1 -columnspan 2 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'select ->', -justify =>'left', -width=>10, -command => sub {$c=$c+1;if ($c>2){$c=0};$key=$keys_list[$c];})->grid(qw/ -row 32 -column 3 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'make list single image', -justify =>'left', -width=>25, -command => sub{&single_image})->grid(qw/ -row 34 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'image', -width=>10, -command => sub{$img=$selected_file;})->grid(qw/ -row 34 -column 1 -columnspan 2  -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'xy file', -width=>10, -command => sub{$xy_file=$selected_file;})->grid(qw/ -row 34 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'all subdirs images ->   all xy lists', -justify =>'left', -width=>25, -command => sub{&all_images})->grid(qw/ -row 36 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'image dir', -width=>10, -command => sub{$img_dir=$selected_dir;&speak;})->grid(qw/ -row 36 -column 1 -columnspan 2  -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'xy files dir', -width=>10, -command => sub{$xy_file_dir=$selected_dir;&speak})->grid(qw/ -row 36 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'copy a text file: times', -justify =>'left', -width=>25, -command => sub{&duplicates})->grid(qw/ -row 40 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$dupes, -width=>5)->grid(qw/ -row 40 -column 1 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'shuffle IMAGES!: lists, cuts', -justify =>'left', -width=>25, -command => sub{&randomize()})->grid(qw/ -row 41 -column 0 -sticky w/);
$entry =$frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$random_files, -width=>5)->grid(qw/ -row 41 -column 1 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$ran_frac, -width=>5)->grid(qw/ -row 41 -column 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'double up lines in csv file', -justify =>'left', -width=>25, -command => sub{&double_lines})->grid(qw/ -row 43 -column 0 -sticky w/);

# blank separator
$frame3->Label(-text => '---change coordinates--- ', -font => '{Helvetica} 10')->grid(qw/ -row 44 -column 0 -sticky n/);

# ----- Coordinate converter (centre <-> top-left) -----
$button = $frame3->Label(-font => '{Helvetica} 15', -text => 'canvas width,height:', -justify =>'left', -width=>25)->grid(qw/ -row 45 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$canvas_w, -width=>12)->grid(qw/ -row 45 -column 1 -columnspan 2 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$canvas_h, -width=>12)->grid(qw/ -row 45 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'Centre -> Top-Left', -justify =>'left', -width=>25, -command => sub{&convert_coords('to_tl')})->grid(qw/ -row 46 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'Top-Left -> Centre', -justify =>'left', -width=>25, -command => sub{&convert_coords('to_centre')})->grid(qw/ -row 47 -column 0 -sticky w/);



# blank separator
$frame3->Label(-text => '---scale x,y to new canvas--- ', -font => '{Helvetica} 10')->grid(qw/ -row 50 -column 0 -sticky n/);

# ----- Scale x,y coordinates by image size ratio -----
$button = $frame3->Label(-font => '{Helvetica} 15', -text => 'old width,height:', -justify =>'left', -width=>25 )->grid(qw/ -row 52 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$old_w, -width=>12)->grid(qw/ -row 52 -column 1 -columnspan 2 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$old_h, -width=>12)->grid(qw/ -row 52 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Label(-font => '{Helvetica} 15', -text => 'new width,height:', -justify =>'left', -width=>25 )->grid(qw/ -row 53 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_w_scale, -width=>12)->grid(qw/ -row 53 -column 1 -columnspan 2 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_h_scale, -width=>12)->grid(qw/ -row 53 -column 3 -columnspan 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'file', -justify =>'left', -width=>10, -command => sub{$scale_mode='file'; $listbox2->insert('end',"scale mode = file");$listbox2->see('end');})->grid(qw/ -row 54 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'directory', -justify =>'left', -width=>10, -command => sub{$scale_mode='dir'; $listbox2->insert('end',"scale mode = directory");$listbox2->see('end');})->grid(qw/ -row 54 -column 0 -sticky e/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'select CSV (file mode)', -justify =>'left', -width=>25, -command => sub{$scale_csv_file=$selected_file;&speak_scale;})->grid(qw/ -row 55 -column 0 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'Scale x,y by ratio', -justify =>'left', -width=>25, -command => sub{&scale_coords})->grid(qw/ -row 56 -column 0 -sticky w/);

# blank separator
$frame3->Label(-text => '---reverse .csv order--- ', -font => '{Helvetica} 10')->grid(qw/ -row 57 -column 0 -sticky n/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'reverse lines in file', -justify =>'left', -width=>25, -command => sub{&reverse_lines()})->grid(qw/ -row 58 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'reverse all files in dir', -justify =>'left', -width=>25, -command => sub{&reverse_dir_lines()})->grid(qw/ -row 59 -column 0 -sticky w/);

#$entry = $frame3->Label(-font => '{Helvetica} 15', -text => '', -justify =>'left', -width=>1)->grid(qw/ -row 58 -column 1 -sticky w/);
# blank separator
$frame3->Label(-text => '---- ', -font => '{Helvetica} 10')->grid(qw/ -row 60 -column 0 -sticky n/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'EXIT', -justify =>'left', -width=>25, -command => sub{$mw->destroy()})->grid(qw/ -row 61 -column 0 -sticky w/);
$button = $mw->Button(-font => '{Helvetica} 15', -text => 'UP', -width=>4, -command => \&go_up)->grid(qw/ -row 62 -column 0 -sticky w/); 
my $toggle_btn;            # declare it first
$toggle_btn = $mw->Button(
    -font    => '{Helvetica} 15',
    -text    => 'Show all',
    -width   => 10,
    -command => sub {
        $show_all = !$show_all;
        $toggle_btn->configure(-text => $show_all ? 'Show filtered' : 'Show all');
        refresh_listbox();
    }
)->grid(qw/ -row 62 -column 0 -sticky n/);   # adjust row/column to suit your layout


#if($show_all == 1){$show_all=0};
&refresh_listbox;
MainLoop;


sub extract{

&check_dir();
my @temp;
my $ct=0;
my $text="";
my $ext1="";
my $ext2="";
if ($key eq "image"){$ext1="image";$ext2=""}
if ($key eq "xy"){$ext1="x";$ext2="y"}
if ($key eq "wh"){$ext1="w";$ext2="h"}
my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });

open (my $fh , '<',"$selected_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();

if($values{x} && $values{y} && $key eq "xy"){
$text="file has x and y";
$ext1="x";
$ext2="y";
$temp[$ct]{x}=$values{x};$text="file has x and y";
$temp[$ct]{y}=$values{y};
}

if($values{w} && $values{h} && $key eq "wh"){
$text="file has w and h";
$ext1="w";
$ext2="h";

$temp[$ct]{w}=$values{w};$text="file has w and h";
$temp[$ct]{h}=$values{h};
}

if($values{image} && $key eq "image"){
$text="! file has image";
$ext1="image";
$temp[$ct]{image}=$values{image};$text="file has image";
}

$ct++;

}
say $text;
#say Dumper @temp;

my $file="$save_directory/extracted_$key.list";
open($fh, '>', $file) or die "Could not open file '$file' $!";
for( my $i=0;$i<=$#temp;$i++){
print $fh "$ext1,$temp[$i]{$ext1}";
if ($ext2){
print $fh ",$ext2,$temp[$i]{$ext2}";
}
print $fh "\n";	
}

close $fh;
	}



sub refresh_listbox {
    my $dir = $dir_stack[-1];
    $listbox->delete(0, 'end');

    opendir(my $dh, $dir) or die "Can't open $dir: $!";
    @contents = readdir($dh);
    closedir($dh);

    @contents = sort { lc($a) cmp lc($b) } @contents;

    foreach my $item (@contents) {
        next if $item =~ /^\./;   # skip hidden files/directories

        my $path = File::Spec->catfile($dir, $item);

        if (-d $path) {
            # always show directories (in blue)
            $listbox->insert('end', $item); 
           $listbox->itemconfigure('end', -foreground => 'blue');
        }
        elsif ($show_all || $item =~ /\.(png|jpg|jpeg|list|imgs|xy|csv)$/i) {
            # show all files, or only the allowed extensions
            $listbox->insert('end', $item);
        }
    }
}




sub select_item {
my $selection = $listbox->get('active');
 my $path = File::Spec->catfile($dir_stack[-1], $selection);

    if (-d $path) {
        push @dir_stack, $path;  # Push selected directory to the stack
        refresh_listbox();
        $selected_dir=$path;
 $text="Selected directory: $selected_dir";
 $listbox2->delete('0', 'end');
 $listbox2->insert('0', $text);
 &get_size();
   } elsif (-f $path) {
        $selected_file = $path;
        $text= "selected file = $selected_file";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
    }
refresh_listbox();
}

sub go_up {
    pop @dir_stack if @dir_stack > 1;  # Pop the top directory from the stack if not already at the root
    refresh_listbox();
}

sub static_xy {
if(!$selected_file){$text="select directory of file";$listbox2->insert('end', $text);$listbox2->see('end');return;}
#say $selected_file;	
my $ct=0;
my @temp;
my $file ="$selected_file";

my ($nfile,$directories,$suffix) = fileparse($selected_file); 	
say "file = $file";
say "nfile = $nfile";
say "suffix = $suffix";
say "directories = $directories";
my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });
open (my $fh , '<',"$file")or die"$!";		

while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
 if(!$values{image}){$text="! file does not have image data !";$listbox2->insert('end', $text);$listbox2->see('end');return;}
 if($values{image}){$temp[$ct]{image}=$values{image}}
 if($values{w}){$temp[$ct]{w}=$values{w}}
 if($values{h}){$temp[$ct]{h}=$values{h}}
$temp[$ct]{x}=$static_x;
$temp[$ct]{y}=$static_y;
 $ct++;
}	
@temp = grep { !/^\.{1,2}$/ } @temp;  # Remove "." and ".." entries
@temp = sort numerically @temp;	
close $fh;

my $text=join "","$selected_dir","/","static_$nfile";
#say $text;
#$file="./$save_directory/$selected_dir_image.list";
open($fh, '>', $text) or die "Could not open file '$text' $!";
for( my $i=0;$i<=$#temp;$i++){
print $fh "image,$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h},x,$temp[$i]{x},y,$temp[$i]{y}  \n";
}
close $fh;	
@temp=undef;

	}

sub get_size{
if(!$selected_dir){$text="select directory of file";$listbox2->insert('end', $text);$listbox2->see('end');return;}
#$text="directory is not of jpeg or png";
opendir(my $dh, $selected_dir) or die "Could not open directory: $!";
@files = readdir($dh);
closedir($dh);
@files = grep { !/^\.\.?$/ } @files;
@files= sort numerically @files;
my $file="$selected_dir/$files[0]";	
if ($file =~ /\.png$/i || $file =~ /\.jpg$/i){
($image_width, $image_height) =imgsize($file);
$aspect=$image_height/$image_width;
$text="First file width= $image_width, height= $image_height";
}
$listbox2->insert('end', $text);	
$listbox2->see('end');
@files=undef;
return;
	}
	
sub check_dir{
my ($directory_) = @_;
say $directory_;
# makes directories to save the files in
unless (-d "./$directory_") {mkdir "./$directory_";$text="made directory $directory_";}	

return;
}

sub numerically {
    my ($a_num) = $a =~ /(\d+)/;
    my ($b_num) = $b =~ /(\d+)/;
$a_num //= 0;  # Set $a_num to 0 if it's uninitialized
$b_num //= 0;  # Set $b_num to 0 if it's uninitialized
return $a_num <=> $b_num;
}

sub zoom{
if(!$selected_dir){$text="select directory of file";$listbox2->insert('end', $text);$listbox2->see('end');return;}
#changes w,h in csv file
&check_dir();			
opendir(my $dh, $selected_dir) or die "Can't open $selected_dir: $!";
my  @files = readdir($dh);
closedir($dh);
@files = grep { !/^\.{1,2}$/ } @files;  # Remove "." and ".." entries
@files = sort numerically @files;
#my $file="./zoom_lists_/$selected_dir/$selected_dir.list";
my $file="./$save_directory/zoom.list";

my $pr=1-(($image_width**2)/($new_w**2))**(1/$frames);
if($image_width>$new_w){
$pr=1-(($new_w**2)/($image_width**2))**(1/$frames);
}
open(my $fh, '>', $file) or die "Could not open file '$file' $!";
my ($last,$w,$h)=(0,0,0);
for( my $i=0;$i<=$#files;$i++){
if($i<$start_fr){
$w=$image_width;
$h=$image_width*$aspect;	
	}
if($i>$start_fr && $i<=($start_fr+$frames)){
$w=int(sqrt(($image_width**2)/((1-$pr)**($i-$start_fr))));
$h=$w*$aspect;
$last=$w;
}

if($i>($start_fr+$frames)){
$w=$last;
$h=$w*$aspect;	
}	
print $fh "image,$selected_dir/$files[$i],w,$w,h,$h\n";
}
close $fh;
$text= "wrote csv $save_directory/zoom.list";
$listbox2->insert('end', $text);
$text="done";
$listbox2->insert('end', $text);
$listbox2->see('end');
#@files=undef;
}

sub make_csv {
    &check_dir($save_directory);
    my @temp;
    opendir(my $dh, $selected_dir) or die "Can't open $selected_dir: $!";
    my @files = readdir($dh);
    closedir($dh);

    # Keep only regular files (skip . , .. and any directories)
    @files = grep {
        my $path = "$selected_dir/$_";
        !/^\.{1,2}$/ && -f $path;
    } @files;

    @files = sort numerically @files;

    # add w,h to array
    for (my $i = 0; $i <= $#files; $i++) {
        my $path = "$selected_dir/$files[$i]";
        my ($image_width, $image_height) = imgsize($path);
        $temp[$i]{image} = $files[$i];
        $temp[$i]{w}     = $image_width;
        $temp[$i]{h}     = $image_height;
    }

    my $file = "$save_directory/image_list.csv";
    say $file;
    say "number of files = $#files";

    open(my $fh, '>', $file) or die "Could not open file '$file' $!";
    for (my $i = 0; $i <= $#files; $i++) {
        print $fh "image,$selected_dir/$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h}\n";
    }
    close $fh;

    @temp  = undef;
    @files = undef;

    $text = "wrote csv $file";
    $listbox2->insert('end', $text);
    $text = "done";
    $listbox2->insert('end', $text);
    $listbox2->see('end');
}


sub randomize{
if(!$selected_dir){$text="select directory of file";$listbox2->insert('end', $text);$listbox2->see('end');return;}
# combines random segments from a list of files in a directory	
&check_dir("randomized_lists_");
my @part;
opendir(my $dh, $selected_dir) or die "Can't open $selected_dir: $!";
  my  @files = readdir($dh);
  closedir($dh);
@files = grep { !/^\.{1,2}$/ } @files;  # Remove "." and ".." entries
@files = sort numerically @files;
my ($file,$directories,$suffix) = fileparse($files[0], qr/\.[^.]*$/); 
say $suffix;
if($suffix ne (".png"||".jpg")) {
$text=" NOT a directory of images";
$listbox2->delete('0');
$listbox2->insert('0', $text);
return();
  }
my $k=$#files;
my $chunk=int($k/$ran_frac);# length of kept order
my $ct=0;
while($ct<=$random_files-1){
my $t=0;
while ($t<=$k-1){
my $start = int(rand($k));
for (my $i=0;$i<=$chunk;$i++){
if(($start+$i)<=$k-1){;
$part[$ct][$t]=$files[$start+$i];
$t++;
}}
}
$ct++;
}

$ct=$#files;
my $fh;
my $all=0;
while ($all<=$random_files-1){
#my $chk=@{$part[$all]};
my $file="./$save_directory/random$all.list";
open($fh, '>', $file) or die "Could not open file '$file' $!";
for( my $i=0;$i<$ct;$i++){
my $filepath=join "",$selected_dir,"/",$part[$all][$i];
($image_width, $image_height) =imgsize("$filepath");
#if(!$image_width){$image_width=0;$image_height=0;}
print $fh "image,$filepath,w,$image_width,h,$image_height\n";
}
$all++;
close $fh;	
}
my $nw=$random_files;
$text="wrote $nw file lists to $save_directory/randomNum.list";
$listbox2->insert('end', $text);
$text="done";
$listbox2->insert('end', $text);
$listbox2->see('end');
#@part=undef;
}
		
sub speak{
if($image_file){
$text="image file = $image_file,"; 
$listbox2->insert('end', $text);
#exec 'spd-say "text"';
}
if ($xy_file){
$text="xy file = $xy_file,";
$listbox2->insert('end', $text);

	}		
if ($wh_file){
$text="wh file = $wh_file,";
$listbox2->insert('end', $text);
	}

if ($xy_file_dir){
$text="xy files dir = $xy_file_dir,";
$listbox2->insert('end', $text);
	}
if ($img_dir){
$text="images dir = $img_dir,";
$listbox2->insert('end', $text);
	}

$listbox2->see('end');
}

sub add_xy{
if(!$selected_dir){$text="select directory of file";$listbox2->insert('end', $text);$listbox2->see('end');return;}
my @temp;
# adds xy from a list to images list
&check_dir($save_directory);
say " image file =$image_file";
my $ct=0;
my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });
open ( my $fh , '<',"$image_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
 if($values{image}){$temp[$ct]{image}=$values{image}}else{$temp[$ct]{image}="";$text="!there is no image";}
($image_width, $image_height) =imgsize($values{image});
 if($values{x}){$temp[$ct]{x}=$values{x}}else{$temp[$ct]{x}=""}
 if($values{y}){$temp[$ct]{y}=$values{y}}else{$temp[$ct]{y}=""}
 if($values{w}){$temp[$ct]{w}=$values{w}}else{$temp[$ct]{w}=$image_width}
 if($values{h}){$temp[$ct]{h}=$values{h}}else{$temp[$ct]{h}=$image_height}
 $ct++;
}
close $fh;	
$ct=0;
open ($fh , '<',"$xy_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
 if(!$values{x}){$text="! file does not have xy data !";$listbox2->insert('end', $text);$listbox2->see('end');return;}
 if($values{x}){$temp[$ct]{x}=$values{x}}
 if($values{y}){$temp[$ct]{y}=$values{y}}
 $ct++;
}	
@temp = grep { !/^\.{1,2}$/ } @temp;  # Remove "." and ".." entries
@temp = sort numerically @temp;
for( my $i=0;$i<=$#temp;$i++){
$temp[$i]{image}//=$temp[$i-1]{image};
$temp[$i]{w}//=$temp[$i-1]{w};
$temp[$i]{h}//=$temp[$i-1]{h};
$temp[$i]{x}//=$temp[$i-1]{x};
$temp[$i]{y}//=$temp[$i-1]{y};
#print $fh "image,$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h},x,$temp[$i]{x},y,$temp[$i]{y}\n";
}
my $file="./$save_directory/added_xy.list";
open($fh, '>', $file) or die "Could not open file '$file' $!";
for( my $i=0;$i<=$#temp;$i++){
print $fh "image,$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h},x,$temp[$i]{x},y,$temp[$i]{y}\n";
}
close $fh;	
#@temp=undef;
$listbox2->insert('end', $text);
$text= "wrote csv ./$save_directory/added_xy.list";
$listbox2->insert('end', $text);
$text="done";
$listbox2->insert('end', $text);
$listbox2->see('end');
@temp=undef;
	}
	
sub add_wh{
if(!$selected_dir){$text="select directory of file";$listbox2->insert('end', $text);$listbox2->see('end');return;}
my @temp;
# adds xy from a list to images list
&check_dir($save_directory);
say " wh file =$wh_file";
my $ct=0;
my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });
say "image_file =$image_file";
open ( my $fh , '<',"$image_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();

if($values{image}){$temp[$ct]{image}=$values{image}}else {$temp[$ct]{image}=""}
if($values{image}){($image_width, $image_height) =imgsize($values{image})}
if($values{x}){$temp[$ct]{x}=$values{x}}else {$temp[$ct]{x}=""}
if($values{y}){$temp[$ct]{y}=$values{y}}else {$temp[$ct]{y}=""}
if($values{w}){$temp[$ct]{w}=$values{w}}else {$temp[$ct]{w}=""}
if($values{h}){$temp[$ct]{h}=$values{h}}else {$temp[$ct]{h}=""}
 $ct++;
}
close $fh;	
$ct=0;
say "wh_file = $wh_file";
open ($fh , '<',"$wh_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
  if(!$values{w}){$text="! file does not have wh data !";$listbox2->insert('end', $text);$listbox2->see('end');return;}
 if($values{w}){$temp[$ct]{w}=$values{w}}
 if($values{h}){$temp[$ct]{h}=$values{h}}
 $ct++;
}	
@temp = grep { !/^\.{1,2}$/ } @temp;  # Remove "." and ".." entries
@temp = sort numerically @temp;
my $file="./$save_directory/added_wh.list";
open($fh, '>', $file) or die "Could not open file '$file' $!";
for( my $i=0;$i<=$#temp;$i++){
$temp[$i]{image}//=$temp[$i-1]{image};
$temp[$i]{w}//=$temp[$i-1]{w};
$temp[$i]{h}//=$temp[$i-1]{h};
$temp[$i]{x}//=$temp[$i-1]{x};
$temp[$i]{y}//=$temp[$i-1]{y};
print $fh "image,$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h},x,$temp[$i]{x},y,$temp[$i]{y}\n";
}
close $fh;	
@temp=undef;
$text= "wrote csv $save_directory/added_wh.list";
$listbox2->insert('end', $text);
$text="done";
$listbox2->insert('end', $text);
$listbox2->see('end');
	}
	
sub add_image{
if(!$selected_dir){$text="select directory of file";$listbox2->insert('end', $text);$listbox2->see('end');return;}
my @temp;
# adds images from a list to xy list
&check_dir($save_directory);
say " xy file =$xy_file";
my $ct=0;
my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });
open ( my $fh , '<',"$xy_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
 if($values{image}){$temp[$ct]{image}=$values{image}}else{$temp[$ct]{image}="";$text="!there is no image";}
($image_width, $image_height) =imgsize($values{image});
 if($values{x}){$temp[$ct]{x}=$values{x}}else{$temp[$ct]{x}="";}
 if($values{y}){$temp[$ct]{y}=$values{y}}else{$temp[$ct]{y}="";}
 if($values{w}){$temp[$ct]{w}=$values{w}}else{$temp[$ct]{w}="";}
 if($values{h}){$temp[$ct]{h}=$values{h}}else{$temp[$ct]{h}="";}
 $ct++;
}
close $fh;	

$ct=0;
open ($fh , '<',"$image_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();

 if(!$values{image}){$text="! file does not have image data !";$listbox2->insert('end', $text);$listbox2->see('end');return;}
 if($values{image}){$temp[$ct]{image}=$values{image}}
 $ct++;
}	
@temp = grep { !/^\.{1,2}$/ } @temp;  # Remove "." and ".." entries
@temp = sort numerically @temp;
for( my $i=0;$i<=$#temp;$i++){
$temp[$i]{image}//=$temp[$i-1]{image};
$temp[$i]{w}//=$temp[$i-1]{w};
$temp[$i]{h}//=$temp[$i-1]{h};
$temp[$i]{x}//=$temp[$i-1]{x};
$temp[$i]{y}//=$temp[$i-1]{y};
#print $fh "image,$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h},x,$temp[$i]{x},y,$temp[$i]{y}\n";
}
my $file="./$save_directory/added_image.list";
open($fh, '>', $file) or die "Could not open file '$file' $!";
for( my $i=0;$i<=$#temp;$i++){
print $fh "image,$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h},x,$temp[$i]{x},y,$temp[$i]{y}\n";
}
close $fh;	
#@temp=undef;
$listbox2->insert('end', $text);
$text= "wrote csv ./$save_directory/added_image.list";
$listbox2->insert('end', $text);
$text="done";
$listbox2->insert('end', $text);
$listbox2->see('end');
@temp=undef;	
	}
		
sub add_self_wh{
say "here add self";

if(!$selected_file){$text="select a file";$listbox2->insert('end', $text);$listbox2->see('end');return}
#my $images= $selected_dir;
my @temp;
# adds wh of the images
&check_dir($save_directory);
my $ct=0;
my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });
open ( my $fh , '<',"$selected_file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
say "x\b";
if($values{image}){$temp[$ct]{image}=$values{image}}
else {$text="! file does not have image data !";
	$listbox2->insert('end', $text);
	$listbox2->see('end');
	return;
	}
my $file=$temp[$ct]{image};
if (!-e $file){$text= "error with name of file, image file does not exist";$listbox2->insert('end', $text);$listbox2->see('end');}
say $file;
($image_width,$image_height) =imgsize($file);
#say "$image_width  $image_height";
$temp[$ct]{w}=$image_width;
$temp[$ct]{h}=$image_height;
if($values{x}){$temp[$ct]{x}=$values{x}}else{$temp[$ct]{x}=""};
if($values{y}){$temp[$ct]{y}=$values{y}}else{$temp[$ct]{y}=""};
$ct++;
}
close $fh;	
#@temp= sort numerically @temp;
@temp = grep { !/^\.{1,2}$/ } @temp;  # Remove "." and ".." entries
@temp = sort numerically @temp;
for( my $i=0;$i<=$#temp;$i++){
$temp[$i]{image}//=$temp[$i-1]{image};
$temp[$i]{w}//=$temp[$i-1]{w};
$temp[$i]{h}//=$temp[$i-1]{h};
$temp[$i]{x}//=$temp[$i-1]{x};
$temp[$i]{y}//=$temp[$i-1]{y};
#say Dumper @temp;
my $file="./$save_directory/added_self_wh.list";
open($fh, '>', $file) or die "Could not open file '$file' $!";
for( my $i=0;$i<=$#temp-1;$i++){
print $fh "image,$temp[$i]{image},w,$temp[$i]{w},h,$temp[$i]{h},x,$temp[$i]{x},y,$temp[$i]{y}\n";
}
close $fh;	

$text= "wrote csv ./$save_directory/added_self_wh.list";
$listbox2->insert('end', $text);
$text="done";
$listbox2->insert('end', $text);
$listbox2->see('end');
@temp=undef;	
	}		
}


sub change_suffix {
    return unless $selected_dir;

    opendir(my $dh, $selected_dir) or die "Could not open directory: $!";
    my @files = grep { !/^\.\.?$/ && -f File::Spec->catfile($selected_dir, $_) } readdir($dh);
    closedir($dh);

    @files = sort numerically @files;
    $listbox2->insert('end', @files) if $listbox2;
    $listbox2->see('end');
    # Ensure the new suffix has exactly one leading dot
    my $suffix = $new_suffix // "";
    $suffix =~ s/^\.+//;          # strip any leading dots
    $suffix = ".$suffix" if length $suffix;

    for my $file (@files) {
        my ($name, $dirs, $old_suffix) = fileparse($file, qr/\.[^.]*$/);
        my $old_path = File::Spec->catfile($selected_dir, $file);
        my $new_path = File::Spec->catfile($selected_dir, $name . $suffix);

        #say "$old_path  ->  $new_path";
        rename $old_path, $new_path or warn "Could not rename $old_path: $!";
    }

    $listbox2->insert('end', "change suffix done") if $listbox2;
    $listbox2->see('end');
    $listbox->update if $listbox;
}



# Remove intermediate number groups that break sorting.
# trees-02-list-004.png  →  trees-list-004.png
sub clean_numbers_in_names {
    if (!$selected_dir) {
        $text = "select a directory first";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    opendir(my $dh, $selected_dir) or die "Cannot open $selected_dir: $!";
    my @files = grep { !/^\.\.?$/ && -f "$selected_dir/$_" } readdir($dh);
    closedir($dh);

    my $changed = 0;
    for my $file (@files) {
        my $new = $file;
        # Remove the first hyphenated number group that is not at the very end
        # (keeps a trailing -004 or _004 style sequence)
        $new =~ s/-\d+(?=-)//;
        $new =~ s/_\d+(?=_)//;

        next if $new eq $file;

        my $oldpath = "$selected_dir/$file";
        my $newpath = "$selected_dir/$new";

        if (-e $newpath) {
            $listbox2->insert('end', "SKIPPED (exists): $new");
            $listbox2->see('end');
            next;
        }

        if (rename($oldpath, $newpath)) {
            $listbox2->insert('end', "$file  →  $new");
            $listbox2->see('end');
            $changed++;
        }
        else {
            $listbox2->insert('end', "Failed: $file ($!)");
            $listbox2->see('end');       
       }
    }

    $text = $changed ? "cleaned $changed filenames" : "no names needed cleaning";
    $listbox2->insert('end', $text);
    $listbox2->see('end');
    refresh_listbox();
}

sub single_image{
#my $img=$selected_file;
say	"$img add to $xy_file";
return();
	}
	
sub all_images2{
&check_dir($save_directory);
my @temp_img;
my @merged;
my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });

say	"$img_dir add to $xy_file_dir";
# get the files of xy paths in the directory into an array
opendir(my $dh, $xy_file_dir) or die "Could not open directory: $!";
my @xy_files = readdir($dh);
closedir($dh);
@xy_files = grep { !/^\.\.?$/ } @xy_files;
@xy_files= sort numerically @xy_files;
#if ($file =~ /\.png$/i || $file =~ /\.jpg$/i)
my $levels=$#xy_files;
say " levels = $levels";
# get the images in the directory into an array
opendir($dh, $img_dir) or die "Could not open directory: $!";
my @image_files = readdir($dh);
closedir($dh);
@image_files = grep { !/^\.\.?$/ } @image_files;
@image_files= sort numerically @image_files;
for( my $i=0;$i<=$#image_files-1;$i++){
($image_width, $image_height) =imgsize("$img_dir/$image_files[$i]");
$temp_img[$i]{image}="$img_dir/$image_files[$i]";
$temp_img[$i]{w}=$image_width;
$temp_img[$i]{h}=$image_height;
}
#say Dumper(\@temp_img);
my $chk=$#image_files;
say " images = $chk";
#return;
@image_files=undef;
#----------
# if theres no more images go to first??
#combine the image and xy files. ONE image to each XY file
for (my $i=0;$i<=$levels;$i++){
#open each xy file and get the x y positions into an array.
open (my $fh , '<',"$xy_file_dir/$xy_files[$i]")or die"$!";		
my $ct=0;
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
$merged[$i][$ct]{x}=$values{x};
$merged[$i][$ct]{y}=$values{y}; 	
$merged[$i][$ct]{image}=$temp_img[$i]{image};
$merged[$i][$ct]{w}=$temp_img[$i]{w};
$merged[$i][$ct]{h}=$temp_img[$i]{h};
#print $dh "image,$img_dir/$merged[$i][$ct]{image},w,$merged[$i][$ct]{w},h,$merged[$i][$ct]{h},x,$merged[$i][$ct]{x},y,$merged[$i][$ct]{y}\n";
$ct++;
}
#close $dh;

#$t++;
close $fh;
}

my $check=$#merged;
say $check;


for (my $i=0;$i<=$#merged;$i++){
my $this_level=(scalar @{$merged[$i]})-1;
say $this_level;
my $print_file=sprintf("$save_directory/level%03d.list",$i);
open($dh, '>', $print_file) or die "Could not open file '$print_file' $!";

for (my $ct=0;$ct<=$this_level;$ct++){
print $dh "image,$merged[$i][$ct]{image},w,$merged[$i][$ct]{w},h,$merged[$i][$ct]{h},x,$merged[$i][$ct]{x},y,$merged[$i][$ct]{y}\n";
}
close $dh;
}
return;
	}
#---- new all images-----#
sub all_images {
    &check_dir($save_directory);

    my $csv = Text::CSV->new({ binary => 1, auto_diag => 1, eol => "\n" });

    # --- collect and sort CSV files ---
    opendir(my $xy_dh, $xy_file_dir) or die "Could not open $xy_file_dir: $!";
    my @xy_files = grep { /\.csv$/i && !/^\.\.?$/ } readdir($xy_dh);
    closedir($xy_dh);
    @xy_files = sort numerically @xy_files;

    # --- collect and sort image subdirectories ---
    opendir(my $img_dh, $img_dir) or die "Could not open $img_dir: $!";
    my @img_subdirs = grep { -d File::Spec->catdir($img_dir, $_) && !/^\.\.?$/ } readdir($img_dh);
    closedir($img_dh);
    @img_subdirs = sort numerically @img_subdirs;

    my $pairs = @xy_files < @img_subdirs ? @xy_files : @img_subdirs;
    say "Pairing $pairs CSV/image-dir sets";

    for my $i (0 .. $pairs - 1) {
        my $csv_name = $xy_files[$i];
        my $subdir   = $img_subdirs[$i];
        my $subdir_path = File::Spec->catdir($img_dir, $subdir);

        # load images from this subdirectory
        opendir(my $sdh, $subdir_path) or die "Could not open $subdir_path: $!";
        my @images = grep { /\.(png|jpe?g|gif|bmp|tiff?)$/i && !/^\.\.?$/ } readdir($sdh);
        closedir($sdh);
        @images = sort numerically @images;

        my @temp_img;
        for my $img (@images) {
            my $full = File::Spec->catfile($subdir_path, $img);
            my ($w, $h) = imgsize($full);
            push @temp_img, {
                image => $full,
                w     => $w // 0,
                h     => $h // 0,
            };
        }

        my $num_images = @temp_img;
        if ($num_images == 0) {
            warn "No images in $subdir_path – skipping $csv_name\n";
            next;
        }

        # open input CSV
        open my $in_fh, '<', File::Spec->catfile($xy_file_dir, $csv_name)
            or die "Cannot open $csv_name: $!";

        # prepare output CSV
        my $out_name = $csv_name;   # same name in save dir
        open my $out_fh, '>', File::Spec->catfile($save_directory, $out_name)
            or die "Cannot write $out_name: $!";

        my $img_idx = 0;
        while (my $line = <$in_fh>) {
##############
$csv->parse($line) or die "CSV parse error on line: $line";
my @fields = $csv->fields();

my ($x_val, $y_val);
for (my $j = 0; $j < @fields - 1; $j++) {
    if ($fields[$j] eq 'x') {
        $x_val = $fields[$j + 1];
    } elsif ($fields[$j] eq 'y') {
        $y_val = $fields[$j + 1];
    }
}
next unless defined $x_val && defined $y_val;

# then the rest stays the same
my $img = $temp_img[$img_idx % $num_images];
$img_idx++;

my $out_line = sprintf(
    #'image,"%s",w,%d,h,%d,x,%s,y,%s',
    'image,%s,w,%d,h,%d,x,%s,y,%s',
    $img->{image},
    $img->{w},
    $img->{h},
    $x_val,
    $y_val
);
print $out_fh "$out_line\n"; 
 

        }

        close $in_fh;
        close $out_fh;
        say "Wrote $out_name (cycled $num_images images across input lines)";
    }
}


	
sub duplicates{
if (!$selected_file){return;};
my $dir ="duplicates_";	
unless (-d $dir){$text="making directory duplicates";
$listbox2->insert('end', $text);
$listbox2->see('end');
mkdir "duplicates_";
}
die "Source file '$selected_file' does not exist\n" unless -f $selected_file;
die "Count must be >= 1\n" unless $dupes >= 1;
my ($file,$directories,$suffix) = fileparse($selected_file, qr/\.[^.]*$/);
my ($base) = $selected_file =~ /^(.*?)(?:\.list)?$/;
say "base =$base";
    for my $i (1..$dupes) {
        my $number = sprintf("%04d", $i);             # 0001, 0002, etc
        my $dest_file = "duplicates_/$file-$number$suffix";         # preserve .list at end
        copy($selected_file, $dest_file) or warn "Failed to copy to $dest_file: $!";
    }
         $text = "copied to duplicates_ $dupes times";
        $listbox2->insert('end', $text);
        $listbox2->see('end');   
return();	
	}


sub add_offset{
say "offset";		
make_path("$save_directory/offset");	
	
my $ct=0;
my @temp;

opendir(my $dh, $selected_dir) or die "Could not open directory: $!";
my @csv_files = readdir($dh);
closedir($dh);

@csv_files = grep { !/^\.\.?$/ } @csv_files;
@csv_files= sort numerically @csv_files;

my $files =$#csv_files;
say $files;
   my $csv = Text::CSV->new ();

for my $i(0..$files){
my $ct=0;
open (my $fh , '<',"$selected_dir/$csv_files[$i]")or die"$!";		

while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
#if(!$values{x}){$text="! file does not have x,y data !";$listbox2->insert('end', $text);return;}

 if($values{image}){$temp[$i][$ct]{image}=$values{image}}
 if($values{x}){$temp[$i][$ct]{x}=$values{x}+$offset_x}
 if($values{y}){$temp[$i][$ct]{y}=$values{y}+$offset_y}
 if($values{w}){$temp[$i][$ct]{w}=$values{w}}
 if($values{h}){$temp[$i][$ct]{h}=$values{h}}

 $ct++;
}	
close $fh;
}
@temp = grep { !/^\.{1,2}$/ } @temp;  # Remove "." and ".." entries
@temp = sort numerically @temp;	

my $list =$#temp;
my $items;

 $csv = Text::CSV->new({ binary => 1, eol => "\n" })
        or die "Cannot use Text::CSV: " . Text::CSV->error_diag();
for (my $i = 0; $i <= $list; $i++) {
    my $items = scalar @{$temp[$i]};

    # Write doubled array to CSV
    my $csv = Text::CSV->new({ binary => 1, eol => "\n" })
        or die "Cannot use Text::CSV: " . Text::CSV->error_diag();

    my $csv_file = sprintf(("$save_directory/offset/file%03d.csv",$i));
    open my $fh, ">", $csv_file or die "Cannot write $csv_file: $!";

    # Header row (if wanted)
    $csv->print($fh, [qw(image w h x y)]);

    # Write data
    for my $row (@{$temp[$i]}) {
    
        $csv->print($fh, [ $row->{image}, $row->{w}, $row->{h} , $row->{x}, $row->{y} ]);
    }

    close $fh;
}
	}

sub double_lines {
    say $selected_dir;
    check_dir('double_lines');          # assumes this creates the output dir

    return unless $selected_dir && -d $selected_dir;

    opendir(my $dh, $selected_dir) or die "Can't open $selected_dir: $!";
    my @csv_files = grep { /\.csv$/i && -f "$selected_dir/$_" } readdir($dh);
    closedir $dh;

    @csv_files = sort numerically @csv_files;

    for my $file (@csv_files) {
        my $in_path  = "$selected_dir/$file";
        my $out_path = "double_lines/$file";   # adjust path as needed

        open my $in,  '<', $in_path  or die "Can't open $in_path: $!";
        open my $out, '>', $out_path or die "Can't create $out_path: $!";

        while (my $line = <$in>) {
            chomp $line;
            next if $line =~ /^\s*$/;          # skip blank lines (optional)

            # Duplicate the line
            print $out "$line\n";
            print $out "$line\n";
        }

        close $in;
        close $out;
        say "Doubled: $file";
    }
}



# ============================================================
# Coordinate converter: centre-relative <-> top-left
# ============================================================

sub trim {
    my $s = shift // '';
    $s =~ s/^\s+|\s+$//g;
    return $s;
}

sub parse_num {
    my $s = trim(shift // '');
    return undef unless $s =~ /^-?\d+(?:\.\d+)?$/;
    return 0 + $s;
}

sub convert_centre_to_tl {
    my ($cx, $cy, $cw, $ch, $iw, $ih) = @_;
    return (
        (($cw - $iw) / 2) + $cx,
        (($ch - $ih) / 2) + $cy
    );
}

sub convert_tl_to_centre {
    my ($tx, $ty, $cw, $ch, $iw, $ih) = @_;
    return (
        $tx - (($cw - $iw) / 2),
        $ty - (($ch - $ih) / 2)
    );
}

sub format_num {
    my $n = shift;
    return ($n == int($n)) ? int($n) : sprintf("%.4f", $n);
}

sub line_to_hash {
    my ($csv, $line) = @_;
    return undef if !defined $line || $line =~ /^\s*$/;
    chomp $line;
    my $ok = $csv->parse($line);
    my @fields = $ok ? $csv->fields : split /,/, $line;
    my %h;
    if (@fields >= 2) {
        $h{_type} = trim($fields[0]);
        $h{_path} = trim($fields[1]);
    }
    for (my $i = 2; $i < @fields - 1; $i += 2) {
        my $lab = lc trim($fields[$i]);
        my $val = trim($fields[$i+1]);
        $h{$lab} = $val if $lab ne '';
    }
    return \%h;
}

sub hash_to_line {
    my ($csv, $h) = @_;
    my @out;
    push @out, $h->{_type} if exists $h->{_type};
    push @out, $h->{_path} if exists $h->{_path};
    for my $k (qw(w h x y)) {
        push @out, $k, $h->{$k} if exists $h->{$k};
    }
    for my $k (sort keys %$h) {
        next if $k =~ /^_/ || $k =~ /^(w|h|x|y)$/;
        push @out, $k, $h->{$k};
    }
    return $csv->combine(@out) ? $csv->string : join(',', @out);
}

sub process_coord_file {
    my ($in_path, $out_path, $cw, $ch, $direction) = @_;
    my $csv = Text::CSV->new({ binary => 1, auto_diag => 0 })
        or return "CSV parser failed";

    open my $in, '<', $in_path or return "Cannot open $in_path: $!";
    my @out_lines;
    my $changed = 0;
    while (my $line = <$in>) {
        my $h = line_to_hash($csv, $line);
        if (!$h) {
            push @out_lines, $line;
            next;
        }
        my $iw = parse_num($h->{w});
        my $ih = parse_num($h->{h});
        my $ox = parse_num($h->{x});
        my $oy = parse_num($h->{y});
        if (defined $ox && defined $oy && defined $iw && defined $ih) {
            my ($nx, $ny) = ($direction eq 'to_tl')
                ? convert_centre_to_tl($ox, $oy, $cw, $ch, $iw, $ih)
                : convert_tl_to_centre($ox, $oy, $cw, $ch, $iw, $ih);
            $h->{x} = format_num($nx);
            $h->{y} = format_num($ny);
            $changed++;
        }
        push @out_lines, hash_to_line($csv, $h);
    }
    close $in;

    open my $out, '>', $out_path or return "Cannot write $out_path: $!";
    print $out "$_\n" for @out_lines;
    close $out;
    return "OK ($changed rows)";
}

sub convert_coords {
    my $direction = shift // 'to_tl';
    if (!$selected_dir || !-d $selected_dir) {
        $text = "select a directory first";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }
    my $cw = parse_num($canvas_w);
    my $ch = parse_num($canvas_h);
    unless (defined $cw && defined $ch) {
        $text = "canvas width and height must be numbers";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    &check_dir();
    my $suffix = ($direction eq 'to_tl') ? 'to_topleft' : 'to_centre';
    my $out_dir = "$save_directory/$suffix";
    make_path($out_dir) unless -d $out_dir;

    my @csvs = glob(File::Spec->catfile($selected_dir, '*.csv'));
    # also catch .list files that are CSV-like
    push @csvs, glob(File::Spec->catfile($selected_dir, '*.list'));
    unless (@csvs) {
        $text = "No .csv or .list files in $selected_dir";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    my ($ok, $fail) = (0, 0);
    for my $f (@csvs) {
        next unless -f $f;
        my $base = basename($f);
        my $out_file = File::Spec->catfile($out_dir, $base);
        my $res = process_coord_file($f, $out_file, $cw, $ch, $direction);
        if ($res =~ /^OK/) {
            $ok++;
            $listbox2->insert('end', "$base: $res");
            $listbox2->see('end');
        } else {
            $fail++;
            $listbox2->insert('end', "$base: ERROR - $res");
            $listbox2->see('end');
        }
    }
    $text = "Converted $ok file(s) ($fail failed) -> $out_dir";
    $listbox2->insert('end', $text);
    $listbox2->see('end');
}



# ============================================================
# Scale x,y coordinates by image size ratio
# Supports single file or all files in selected directory
# ============================================================

sub speak_scale {
    if ($scale_csv_file) {
        $text = "scale CSV = $scale_csv_file";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
    } else {
        $text = "no CSV selected for scaling";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
    }
}

sub scale_one_file {
    my ($in_path, $out_path, $scale_x, $scale_y) = @_;
    my $csv = Text::CSV->new({ binary => 1, auto_diag => 0 })
        or return "CSV parser failed";

    open my $in, '<', $in_path or return "Cannot open $in_path: $!";
    my @out_lines;
    my $changed = 0;

    while (my $line = <$in>) {
        my $h = line_to_hash($csv, $line);
        if (!$h) {
            push @out_lines, $line;
            next;
        }
        my $ox = parse_num($h->{x});
        my $oy = parse_num($h->{y});
        if (defined $ox && defined $oy) {
            $h->{x} = format_num($ox * $scale_x);
            $h->{y} = format_num($oy * $scale_y);
            $changed++;
        }
        push @out_lines, hash_to_line($csv, $h);
    }
    close $in;

    open my $out, '>', $out_path or return "Cannot write $out_path: $!";
    print $out "$_\n" for @out_lines;
    close $out;
    return "OK ($changed rows)";
}

sub scale_coords {
    my $ow = parse_num($old_w);
    my $oh = parse_num($old_h);
    my $nw = parse_num($new_w_scale);
    my $nh = parse_num($new_h_scale);

    unless (defined $ow && defined $oh && defined $nw && defined $nh && $ow > 0 && $oh > 0) {
        $text = "old/new width and height must be positive numbers";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    my $scale_x = $nw / $ow;
    my $scale_y = $nh / $oh;

    &check_dir();

    if ($scale_mode eq 'file') {
        if (!$scale_csv_file || !-f $scale_csv_file) {
            $text = "file mode: select a CSV/list first";
            $listbox2->insert('end', $text);
            $listbox2->see('end');
            return;
        }
        my ($base, $dir, $suffix) = fileparse($scale_csv_file, qr/\.[^.]*$/);
        my $out_file = "$save_directory/${base}_scaled${suffix}";
        my $res = scale_one_file($scale_csv_file, $out_file, $scale_x, $scale_y);
        $text = "File mode: $res  (scale_x=$scale_x scale_y=$scale_y) -> $out_file";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
    }
    else {
        # directory mode
        if (!$selected_dir || !-d $selected_dir) {
            $text = "directory mode: select a directory first";
            $listbox2->insert('end', $text);
            $listbox2->see('end');
            return;
        }
        my $out_dir = "$save_directory/scaled";
        make_path($out_dir) unless -d $out_dir;

        my @files = (
            glob(File::Spec->catfile($selected_dir, '*.csv')),
            glob(File::Spec->catfile($selected_dir, '*.list'))
        );
        unless (@files) {
            $text = "No .csv or .list files in $selected_dir";
            $listbox2->insert('end', $text);
            $listbox2->see('end');
            return;
        }

        my ($ok, $fail) = (0, 0);
        for my $f (@files) {
            next unless -f $f;
            my $base = basename($f);
            my $out_file = File::Spec->catfile($out_dir, $base);
            my $res = scale_one_file($f, $out_file, $scale_x, $scale_y);
            if ($res =~ /^OK/) {
                $ok++;
                $listbox2->insert('end', "$base: $res");
            } else {
                $fail++;
                $listbox2->insert('end', "$base: ERROR - $res");
            }
         
        }
        $text = "Directory mode: scaled $ok file(s) ($fail failed)  scale_x=$scale_x scale_y=$scale_y -> $out_dir";
        $listbox2->insert('end', $text);
    }
        $listbox2->see('end');
}
##########

# Last line becomes first. Rows stay image,path,x,xNum,y,yNum,w,wNum,h,hNum
sub reverse_one_file {
    my ($in_path, $out_path) = @_;
    my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });
    open(my $in, '<', $in_path) or die "$!";

    my @temp;
    while (my $line = <$in>) {
        next if $line =~ /^\s*$/;
        chomp $line;
        my $ok = $csv->parse($line);
        my @fields = $ok ? $csv->fields : split(/,/, $line);
        next unless @fields;

        my %values = @fields;
        my @order;
        for (my $i = 0; $i < @fields; $i += 2) {
            my $k = $fields[$i];
            next if !defined $k || $k eq '';
            push @order, $k;
        }
        push @temp, { values => \%values, order => \@order };
    }
    close $in;

    unless (@temp) {
        $text = "no lines in $in_path";
        return;
    }

    @temp = reverse @temp;

    open(my $fh, '>', $out_path) or die "Could not open file '$out_path' $!";
    for my $row (@temp) {
        my @out;
        for my $k (@{ $row->{order} }) {
            push @out, $k, ($row->{values}{$k} // '');
        }
        $csv->combine(@out);
        print $fh $csv->string, "\n";
    }
    close $fh;
    return scalar @temp;
}

sub reverse_lines {
    if (!$selected_file || !-f $selected_file) {
        $text = "select a csv/list file first";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    &check_dir();
    my ($nfile) = fileparse($selected_file);
    my $out = "./$save_directory/reversed_$nfile";
    my $n = reverse_one_file($selected_file, $out);
    return unless defined $n;
    $text = "reversed $n lines -> $out";
    $listbox2->insert('end', $text);
    $listbox2->see('end');
}

sub reverse_dir_lines {
    if (!$selected_dir || !-d $selected_dir) {
        $text = "select a directory first";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    &check_dir();
    my $out_dir = "$save_directory/reversed";
    make_path($out_dir) unless -d $out_dir;

    opendir(my $dh, $selected_dir) or die "Can't open $selected_dir: $!";
    my @files = grep { !/^\.\.?$/ && /\.(csv|list)$/i && -f "$selected_dir/$_" } readdir($dh);
    closedir($dh);
    @files = sort numerically @files;

    unless (@files) {
        $text = "no .csv or .list files in $selected_dir";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    my $ok = 0;
    for my $name (@files) {
        my $n = reverse_one_file("$selected_dir/$name", "$out_dir/reversed_$name");
        if (defined $n) {
            $ok++;
            $listbox2->insert('end', "$name: reversed $n lines");
        }
        else {
            $listbox2->insert('end', "$name: $text");
        }
    }
    $text = "reversed $ok file(s) -> $out_dir";
    $listbox2->insert('end', $text);
    $listbox2->see('end');
}



sub rewrite_paths {
    my ($target, $new_prefix) = @_;
    die "Need a file or directory and a new prefix"
        unless $target && defined $new_prefix;

    # Normalise empty / "." prefix to mean "just the filename"
    $new_prefix = "" if !defined $new_prefix || $new_prefix eq "" || $new_prefix eq ".";

    my @files;
    if (-d $target) {
        opendir my $dh, $target or die "Could not open directory $target: $!";
        @files = grep { /\.csv$/i && -f File::Spec->catfile($target, $_) }
                 readdir $dh;
        closedir $dh;
        @files = map { File::Spec->catfile($target, $_) } sort @files;
    }
    elsif (-f $target) {
        @files = ($target);
    }
    else {
        die "Not a file or directory: $target";
    }

    my $csv = Text::CSV->new({ binary => 1, auto_diag => 1, eol => "\n" })
        or die "CSV error: " . Text::CSV->error_diag;

    for my $csv_file (@files) {
        my $tmp = "$csv_file.tmp";
        open my $in,  "<:encoding(utf8)", $csv_file or die $!;
        open my $out, ">:encoding(utf8)", $tmp      or die $!;

        while (my $row = $csv->getline($in)) {
            # second field holds the path (and possibly the ,w,h,x,y… stuff)
            if (@$row >= 2 && length $row->[1]) {
                my ($path, $rest) = split /,/, $row->[1], 2;
                $rest = defined $rest ? ",$rest" : "";

                my ($filename, undef, $suffix) = fileparse($path, qr/\.[^.]*$/);
                my $new_path;

                if ($new_prefix eq "") {
                    # empty prefix → just the bare filename
                    $new_path = "$filename$suffix";
                } else {
                    # normal prefix → join properly (avoids // etc.)
                    $new_path = File::Spec->catfile($new_prefix, "$filename$suffix");
                }

                $row->[1] = $new_path . $rest;
            }
            $csv->print($out, $row);
        }

        close $in;
        close $out;
        rename $tmp, $csv_file or warn "Could not replace $csv_file: $!";
    }

    return scalar @files;   # number of files processed
}
