#!/usr/bin/perl -w
# NAME: imgindex02.pl
# AIM: To read a FOLDER, finding all image files, and preparing a SIMPLE table index
# 14/02/2011 - revisited - genimgindex.pl seems too complicated, so try this one...
# 08/12/2008 - revisited, but has PROBLEM of distorting many images into the FIXED
# display size of 128x128, but does build a SIMPLE index ...
# Also when adding the FULL PATH, leaves 'spaces' in path name, if any.
# Dec 12, 2006 geoff mclane http://geoffair.net/mperl
# Also see genimgindex.pl, which uses Imagemagick, 'identify' app, if installed, to get the image sizes.
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::Spec; # File::Spec->rel2abs($rel); # we are IN the SLN directory, get ABSOLUTE from RELATIVE
use File::stat;
use Cwd;
my $perl_dir = "C:\\Gtools\\perl"; 
unshift(@INC,$perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl'! Check location and \@INC content.\n";
require 'imgsize.pl' or die "Unable to load imgsize.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
    my @tmpsp = split(/\\/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $perl_dir.'\temp.'.$pgmname.'.txt';

my $load_log = 1;
my $add_full_path = 1;	# add full path to file
my $wrap = 4;
my $addlink = 0;
my $add_width_height = 0;
my $load_in_browser = 1;
my $addhdrln = 0; # and following is set of headings
my @headings = qw(Image Image Image Image);
mydie( "ERROR: Heading list NOT equal WRAP size ...\n" ) if ($wrap != scalar @headings);
my $addsize = 1;
my $imgsz = ' width="128" height="128"';

my $in_folder = 'C:\FG\Atlas\Atlas-0.5.0\build\msvc\temp';
my $img_folder = '6';
#my $in_folder = 'C:\Documents and Settings\Geoff McLane\My Documents\Carla';
#my $img_folder = 'enfants';
#my $in_folder = 'C:\Documents and Settings\Geoff McLane\My Documents\Sue';
#my $img_folder = 'pics01';
##my $in_folder = 'C:\HOMEPAGE\Max5\tunisia';
##my $img_folder = '128x128';
##my $img_folder = '640x480';
my $input_dir = $in_folder . '\\' . $img_folder;

my $out_htm_file = 'tempindex2.htm';

# debug
my $dbg_01 = 0;

my @img_list = ();
my %img_sizes = ();
my @warnings = ();
my $cwd = cwd();
my $os = $^O;

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prt("$itm\n");
        }
        prt("\n");
    } else {
        #prt( "\nNo warnings issued.\n\n" );
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings($val);
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

sub is_img_file($) {
	my ($f) = @_;
	my $ret = 0;
	return 1 if ($f =~ /(.*)\.jpg$/i);
	return 2 if ($f =~ /(.*)\.gif$/i);
    return 3 if ($f =~ /(.*)\.png$/i);
	return $ret;
}

sub to_web($) {
	my ($txt) = shift;
	$txt =~ s/\\/\//g;
	return $txt;
}

sub process_img_folder($) {
    my ($in_dir) = @_;
    prt ("Processing directory $in_dir ...\n");
    opendir( DIR, $in_dir) || mydie( "ERROR: Can NOT open $in_dir ... $! ... aborting ...\n" );
    my @files = readdir(DIR);
    closedir DIR;
    prt ("Found ".scalar @files." items in the directory ...\n");
    my ($file,$ff);
    my ($isz,$iwd,$iht);
    $in_dir .= "\\" if !($in_dir =~ /(\\|\/)$/);
    foreach $file (@files) {
        next if (($file eq '.')||($file eq '..'));
        $ff = $in_dir.$file;
        if ( -d $ff ) {
            #prt( "Ignore Directory $file ...\n");
        } elsif (-f $ff) {
            if (is_img_file($file)) {
                push(@img_list, $file );
                if ($add_width_height) {
                    $isz = im_get_image_size($ff);
                    $iwd = im_get_image_width($isz);
                    $iht = im_get_image_height($isz);
                    $img_sizes{$file} = [$isz, $iwd, $iht];
                    prt("$file $iwd x $iht\n") if ($dbg_01);
                }
            }
        } else {
            prt("WARNING: What is THIS [$ff]\n");
        }
    }
    prt ("Found ".scalar @img_list." image files in the directory ...\n");
}

my $html_bgn = <<EOF;
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Language" content="en-gb">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="generator" content="genindex3.pl">
<title>New Image Index</title>
<style type="text/css">
<!-- /* some style 2006.10.20 */
body {
   margin:0cm 1cm;
   background-image:url('../clds3.jpg');
}
h1{
	background:#efefef;
	border-style:solid;
	border-color:#d9e2e2;
	border-width:1px;
	padding-top:2px;
	padding-bottom:2px;
	padding-left:2px;
	padding-right:2px;
	font-size:200%;
	text-align:center;
}
h2 { font-size: 12pt; font-weight: bold; background-color: #CCCCFF }
.ctr { text-align:center; }
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:none;}
a:active {text-decoration:none;} 
a_style {text-decoration:none;}
img_style {margin:0;}

-->
</style>
</head>

<body>
<h1>New Image Index</h1>
<p class="ctr"><a href="../home2.htm">home</a></p>
<div align="center">
  <center>

EOF

my $html_end = <<EOF;
  </table>
  </center>
</div>
<p class="ctr"><a href="../home2.htm">home</a></p>
</body>
</html>
EOF

my $table = '<table border="0" cellpadding="0" cellspacing="0" summary="Table of Images">';

sub sort_of_images($) {
    my ($ril) = @_;
    my $maxcnt = scalar @{$ril};
    my ($i,$file);
    my ($ew,$lon,$ns,$lat,$rew,$rns);
    my ($alat,$alon,$rc,$comb);
    my @arr = ();
    my %lons = ();
    my %lats = ();
    my %combs = ();
    my $min_lon = 200;
    my $max_lon = -200;
    my $min_lat = 200;
    my $max_lat = -200;
    for ($i = 0; $i < $maxcnt; $i++) {
        $file = ${$ril}[$i];
        # e000n43
        if ($file =~ /^(e|w)(\d{3})(n|s)(\d{2})/) {
            $ew = $1;
            $lon = $2;
            $ns = $3;
            $lat = $4;
            $alat = $lat;
            $alon = $lon;
            $lon = -$lon if ($ew eq 'w');
            $lat = -$lat if ($ns eq 's');
            $comb = $ew.$ns;
            #prt("$ew $lon $ns $lat\n");
            $min_lon = $lon if ($lon < $min_lon);
            $max_lon = $lon if ($lon > $max_lon);
            $min_lat = $lat if ($lat < $min_lat);
            $max_lat = $lat if ($lat > $max_lat);
            $lons{$ew} = [ ] if (!defined $lons{$ew});
            $lats{$ns} = [ ] if (!defined $lats{$ns});
            $rew = $lons{$ew};
            $rns = $lats{$ns};
            push(@{$rew},$lon);
            push(@{$rns},$lat);
            $combs{$comb} = [ ] if (!defined $combs{$comb});
            $rc = $combs{$comb};
            push(@{$rc}, [$alon,$alat,$file,0]);
            # exit(1) if ($i > 5);
        } else {
            prt("File [$file] not FG style!\n");
        }
        push(@arr,$file);
    }
    my @keys = qw( wn en ws es );
    my ($key,$done,$ok,$nlon,$nlat,$inw,$ins,$cnt,$cdncnt,$max);
    my $dncnt = 0;
    my @narr = ();
    foreach $comb (@keys) {
        if (defined $combs{$comb}) {
            # ok got some of these
            $rc = $combs{$comb};    # extract the LIST
            $max = scalar @{$rc};
            $cnt = $max;
            $ok = 1;
            prt("Sorting $cnt $comb items...\n");
            while ($cnt) {
                if ($comb =~ /^w/) {
                    $nlon = -200;
                    $inw = 1;
                } else {
                    $nlon = +200;
                    $inw = 0;
                }
                if ($comb =~ /s$/) {
                    $ins = 1;
                    $nlat = 200;
                } else {
                    $ins = 0;
                    $nlat = -200;
                }
                for ($i = 0; $i < $max; $i++) {
                    $alon = ${$rc}[$i][0];
                    $alat = ${$rc}[$i][1];
                    $file = ${$rc}[$i][2];
                    $done = ${$rc}[$i][3];
                    if (!$done) {
                        if ($inw) {
                            $nlon = $alon if ($alon > $nlon);
                        } else {
                            $nlon = $alon if ($alon < $nlon);
                        }
                    }
                }
                for ($i = 0; $i < $max; $i++) {
                    $alon = ${$rc}[$i][0];
                    $alat = ${$rc}[$i][1];
                    $file = ${$rc}[$i][2];
                    $done = ${$rc}[$i][3];
                    if (!$done) {
                        if ($nlon == $alon) {
                            if ($ins) {
                                $nlat = $alat if ($alat < $nlat);
                            } else {
                                $nlat = $alat if ($alat > $nlat);
                            }
                        }
                    }
                }
                $ok = 0;
                for ($i = 0; $i < $max; $i++) {
                    $alon = ${$rc}[$i][0];
                    $alat = ${$rc}[$i][1];
                    $file = ${$rc}[$i][2];
                    $done = ${$rc}[$i][3];
                    if (!$done) {
                        if (($alon == $nlon)&&($alat == $nlat)) {
                            ${$rc}[$i][3] = 1;
                            $dncnt++;
                            $ok = 1;
                            last;
                        }
                    }
                }
                $cdncnt = sprintf("%3d",$dncnt);
                if ($ok) {
                    #prt("$cdncnt: $comb, lon = $nlon, lat = $nlat, file [$file]\n");
                    push(@narr,$file);
                } else {
                    prt("FAILED: $comb, lon = $nlon, lat = $nlat, file [$file]\n");
                }
                $cnt--;
            }
            prt("Done $max $comb items...\n");
        }
    }
    prt("min lat/lon $min_lat/$min_lon, max lat/lon $max_lat/$max_lon\n");
    prt("keys = ");
    foreach $comb (keys %combs) {
        prt("[$comb] ");
    }
    prt(" done=$dncnt, max=$max\n");
    if ($dncnt == $maxcnt) {
        prt("Returning NEW array...\n");
        return @narr;
    }
    return @arr;
}

sub process_img_list($$$) {
    my ($in_dir,$htm_file,$ril) = @_;
    my ($file,$max,$cnt,$ff,$msg,$tcnt,$i);
    my @list = sort_of_images($ril);
    $max = scalar @list;
    if ($max == 0) {
        prt("No images to process...\n");
        return;
    }
    prt( "Creating [$htm_file] as output... with $max images...\n" );
    open OH, ">$htm_file" || mydie( "ERROR: Can NOT create out file $htm_file ... $! ... aborting ...\n");
    $cnt = 0;
    $tcnt = 0;
    print OH $html_bgn;
    print OH $table."\n";
    if ($addhdrln) {
        print OH "<tr>\n";
        $cnt = 0;
        while ($cnt < $wrap) {
            print OH "<th>$headings[$cnt]</th>\n";
            $cnt++;
        }
        print OH "</tr>\n";
    }
    $cnt = 0;
    for ($i = 0; $i < $max; $i++) {
        $file = $list[$i];
        $tcnt++;
        print OH "<tr>\n" if ($cnt == 0);
        if ($add_full_path) {
            $ff = $in_dir . '\\' . $file;
        } else {
            $ff = $img_folder . '\\' . $file;
        }
        $ff = to_web($ff);
        $msg = "<td>";
        $msg .= "<a class=\"a_style\" href=\"$ff\">" if ($addlink);
        $msg .= "<img class=\"img_style\" src=\"$ff\" alt=\"$file $tcnt\"";
        $msg .= $imgsz if ($addsize);
        $msg .= ">";
        $msg .= "</a>" if ($addlink);
        $msg .= "</td>\n";
        print OH $msg;
        $cnt++;
        if ($cnt >= $wrap) {
            print OH "</tr>\n";
            $cnt = 0;
        }
    }
    if ($cnt) {
        while ($cnt < $wrap) {
            $msg = "<td>no image</td>\n";
            print OH $msg;
            $cnt++;
        }
        print OH "</tr>\n";
    }
    print OH $html_end;
    close OH;
    prt("Done, and closed [$htm_file]...\n");
    if ($load_in_browser) {
        prt("Loading [$htm_file] in browser....\n");
        system($htm_file);
    }
}

# ### MAIN ###
open_log($outfile);
parse_args(@ARGV);
process_img_folder($input_dir);
process_img_list($input_dir,$out_htm_file,\@img_list);
pgm_exit(0,"");
# ### END ###


sub parse_args {
    my (@av) = @_;
    while (@av) {


        shift @av;
    }
}

# eof - imgindex.pl
