#!/perl -w
# NAME: imglist.pl
# AIM: Given a folder, search for ALL image files
# 20/04/2013 - add html output
# 08/12/2008 - revisited, and works fine as a SIMPLE LIST
# 19/07/2008 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;     # to split path into ($name, $dir) = fileparse($ff); or ($nm,$dir,$ext) = fileparse( $fil, qr/\.[^.]*/ );
use File::stat; # to get the file date
use File::Spec; # File::Spec->rel2abs($rel);
use Time::HiRes qw( gettimeofday tv_interval );
use Cwd;
my $os = $^O;
my $perl_dir = '/home/geoff/bin';
my $PATH_SEP = '/';
my $temp_dir = '/tmp';
if ($os =~ /win/i) {
    $perl_dir = 'C:\GTools\perl';
    $temp_dir = $perl_dir;
    $PATH_SEP = "\\";
}
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
require 'lib_imgsize.pl' or die "Unable to load 'lib_imgsize.pl' Check paths in \@INC...\n";
# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $temp_dir.$PATH_SEP."temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.1 2013-02-07";
my $load_log = 0;
my $verbosity = 0;
my $out_file = '';
my $in_folder = '';
my $use_rel_dir = 1;
my $html_output = 1;
my $targ_width = 250;
my $column_count = 4;

### program variables
my @warnings = ();
my $cwd = cwd();

my @graf_ext = qw( .jpg .jpeg .gif .png .bmp .ico .mpg .tif );
my @fpfolders = qw( _vti_cnf _vti_pvt _private _derived );

my @imagelist = ();
my $filcnt = 0;
my $dircnt = 0;

# ### DEBUG ###
my $debug_on = 1;
my $def_file = 'C:\FG\18\images';
my $def_out_file = 'C:\FG\18\temp1.htm';

### my $start_time = time();
my $start_time = [gettimeofday];

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

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" ) if (VERB9());
    }
}

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 elapsed_seconds {
    my $elapsed = tv_interval ( $start_time, [gettimeofday]);
    return $elapsed;
}

#########################################################
# Passed an array of extensions,
# check if this is one of them?
#########################################################
sub is_my_ext {
	my ($fil, @exts) = @_;
	my ($nm,$dir,$ext) = fileparse( $fil, qr/\.[^.]*/ );
	foreach my $ex (@exts) {
		if (lc($ex) eq lc($ext)) {
			return 1;
		}
	}
	return 0;
}

############################################
# only looking for GRAPHIC extensions,
# could be extended to others maybe ...
############################################
sub is_graphic_ext {
	my ($fil) = shift;
	return( is_my_ext($fil, @graf_ext) );
}

sub is_fp_folder {
    my ($fdr) = shift;
    my $tst;
    foreach $tst (@fpfolders) {
        if ($tst eq $fdr) {
            return 1;
        }
    }
    return 0;
}

sub get_image_list {
    my ($inf) = shift;
    my ($itm, $ff);
    my @fldrs = ();
	if ( opendir( DIR, $inf ) ) {
		my @files = readdir(DIR);
		closedir DIR;
		foreach $itm (@files) {
			if (($itm eq '.') || ($itm eq '..')) {
				next;
			}
			$ff = $inf . "\\" . $itm;
			if (-d $ff) {
                push(@fldrs,$ff) if !is_fp_folder($itm);
                $dircnt++;
                if (($dircnt % 100) == 0) {
                    prt( "Found ".scalar @imagelist." images ... in $dircnt directories, $filcnt files ... (".elapsed_seconds()." secs)\n" );
                }
                ##last if ($dircnt > 2000);
            } else {
                push(@imagelist, $ff) if (is_graphic_ext($itm));
                $filcnt++;
            }
        }
        foreach $itm (@fldrs) {
            get_image_list($itm);
        }
    } else {
        prt( "ERROR: Failed to OPEN $inf ...\n" );
    }
}

sub show_math {
    my ($wid, $hgt, $tw) = @_;
    my $ratio = $wid / $hgt;
    my ($imgSx, $imgSy);
    if($ratio > 1) {
	    $imgSx = $tw;
    	$imgSy = int( ($tw / $ratio) + 0.5 );
    } else {
	    $imgSx = int( ($tw * $ratio) + 0.5 );
	    $imgSy = $tw;
    }

    prt( "From $wid x $hgt, TARGET maximum $tw, gives $imgSx x $imgSy ... ratio $ratio\n" );

    # use HEIGHT
    $imgSx = int( ($tw * $ratio) + 0.5 );
    $imgSy = $tw;
    prt( "Set HEIGHT: gives $imgSx x $imgSy ... " );
    # use WIDTH
    $imgSx = $tw;
    $imgSy = int( ($tw / $ratio) + 0.5 );
    prt( "Set  WIDTH: gives $imgSx x $imgSy ...\n" );
}

sub get_html_head($) {
    my $tit = shift;
    my $src = path_d2u($in_folder);
    my $htm = <<EOF;
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>
   $tit
  </title>
  <style type="text/css">
.top { text-align : center; }
  </style>
 </head>
 <body>
  <h1 align="center">
   Image list in $src
  </h1>

EOF
    return $htm;
}

sub get_html_table() {
    my $htm = <<EOF;
   <table align="center"
          border="0"
          cellspacing="0"
          cellpadding="0"
          summary="List of images">
EOF
    return $htm;
}

sub get_html_tail() {
    my $htm = <<EOF;
  </body>
</html>
EOF
    return $htm;
}

sub write_html_output($) {
    my $ra = shift; # = \@relfiles
    my $max = scalar @{$ra};
    my ($i,$rf,$ff,$is,$w,$h,$ratio,$n,$d,$e);
    my $tw = $targ_width;
    my ($imgSx, $imgSy,$wrap,$at);
    my $htm = get_html_head("Image List");
    $htm .= '  <div class="top">'."\n";
    $htm .= get_html_table();
    $wrap = 0;
    for ($i = 0; $i < $max; $i++) {
        $rf = ${$ra}[$i][0];
        $ff = ${$ra}[$i][1];
        $is = im_get_image_size($ff);
        $w = im_get_image_width($is);
        $h = im_get_image_height($is);
        $ratio = $w / $h;
        if($ratio > 1) {
            $imgSx = $tw;
            $imgSy = int( ($tw / $ratio) + 0.5 );
        } else {
            $imgSx = int( ($tw * $ratio) + 0.5 );
            $imgSy = $tw;
        }
        $rf = path_d2u($rf);
        ($n,$d,$e) = fileparse( $ff, qr/\.[^.]*/ );
        prt("$rf $w"."x"."$h show $imgSx".'x'."$imgSy, ratio $ratio\n");
        ###show_math($w,$h,$targ_width);
        $htm .= "    <tr>\n" if ($wrap == 0);
        $htm .= "     <td>\n";
        $htm .= '      <a target="_blank" href="'.$rf.'">'."\n";
        $htm .= '       <img src="'.$rf.'" width="'.$imgSx.'" height="'.$imgSy.'"'."\n";
        $htm .= '           alt="';
        $n =~ s/-/ /g;
        $at = "Image $w".'x'."$h $n";
        $at = trim_all($at);
        $htm .= $at.'"'."\n";
        $htm .= '           title="';
        $htm .= $at.'"'.">\n";
        $htm .= "      </a>\n";
        $htm .= "     </td>\n";
        $wrap++;
        if ($wrap == $column_count) {
            $htm .= "    </tr>\n";
            $wrap = 0;
        }

    }
    if ($wrap) {
        while ($wrap < $column_count) {
            $htm .= "     <td>&nbsp;</td>\n";
            $wrap++;
        }
        $htm .= "    </tr>\n";
    }
    #$load_log = 1;
    $htm .= "   </table>\n";
    $htm .= "  </div>\n";
    $htm .= "  <p>Click image to see at full size in a new window<\p>\n";
    $htm .= "  <!-- Generated by $pgmname on ".lu_get_YYYYMMDD_hhmmss_UTC(time())." UTC -->\n";
    $htm .= get_html_tail();
    write2file($htm,$out_file);
    prt("HTML written to [$out_file]\n");
}


sub show_img_list() {
    my $fndcnt = scalar @imagelist;
    my $msg = '';
    my ($i,$file,$on,$od,$olen,$reld,$n,$d,$html);
    $olen = length($out_file);
    prt( "Found $fndcnt images ... in $dircnt directories, $filcnt files ...\n" );
    if ($olen) {
        ($on,$od) = fileparse($out_file);
        $reld = get_relative_path4($in_folder,$od);
        prt("Relative directory [$reld]\n");
    }
    my @relfiles = ();
    for ($i = 0; $i < $fndcnt; $i++) {
        $file = $imagelist[$i];
        if ($olen && $use_rel_dir) {
            ($n,$d) = fileparse($file);
            push(@relfiles,[$reld.$n,$file]);
        }
        $msg .= "$file\n"; 
    }
    if (length($msg)) {
        if ($olen) {
            prt($msg);
            if ($html_output) {
                write_html_output(\@relfiles);
            } else {
                write2file($msg,$out_file);
                prt("List written to [$out_file]\n");
            }
        } else {
            prt("$msg");
            prt("No -o <out_file> given\n");
        }
    }
    prt( "Done $fndcnt images ... (".elapsed_seconds()." secs)\n" );
}

#########################################
### MAIN ###
parse_args(@ARGV);
prt( "Processing folder [$in_folder] ...\n" );
get_image_list($in_folder);
show_img_list();
pgm_exit(0,"");
#########################################
### END MAIN ###


sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = File::Spec->rel2abs($sarg);
                prt("Set out file to [$out_file].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_folder = File::Spec->rel2abs($arg);   # get ABSOLUTE path of input
            if (-d $in_folder) {
                prt("Set input folder to [$in_folder]\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Unable to find in folder [$in_folder]! Check name, location...\n");

            }
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG on is ENABLED!\n");
        if (length($in_folder) ==  0) {
            $in_folder = $def_file;
            prt("Set DEFAULT input to [$in_folder]\n");
        }
        if (length($out_file) == 0) {
            $out_file = $def_out_file;
            prt("Set DEFAULT output to [$out_file]\n");
        }
    }
    if (length($in_folder) ==  0) {
        pgm_exit(1,"ERROR: No input folder found in command!\n");
    }
    if (! -d $in_folder) {
        pgm_exit(1,"ERROR: Unable to find in folder [$in_folder]! Check name, location...\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help  (-h or -?) = This help, and exit 0.\n");
    prt(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prt(" --out <file>  (-o) = Write output to this file.\n");
}


# eof
