%#
%# thumb - given an image, generates
%#	   <img> tag to thumbnail, creating if necessary
%#
<%perl>
    my ($pic) = @_;
    my ($thumb, $path, $root, $tpath, $w, $h, $im, $top, $mode, $tw, $config,
	$jhead);

    $config = $m->comp('config');
    $tw = $config->{thumb_width};
    $jhead = $config->{jhead_path};

    $top = $m->top_comp;
    $path = $top->dir_path;
    $root = $top->source_dir;

    $thumb = $pic;
    $thumb =~ s|^$path|$path/gallery/tmp/thumbs|;
    $thumb =~ s/\.(gif|png)$/.jpg/i;

    $tpath = $thumb;
    $tpath =~ s|^$path|$root|;
    $pic = $r->lookup_uri($pic)->filename;
    die unless -e $pic;

    unless ((stat($tpath))[9] > (stat($pic))[9]) {
	$mode = (stat(_))[2];
	mkpath([dirname($tpath)], 0, 0777) unless -d dirname($tpath);

	## EXIF goodness
	if (!($mode & 011) && $pic =~ /\.jpg$/i && $tw <= 160 && $jhead) {
	    open(JHEAD, '-|') || exec($jhead, '-st', $tpath, $pic);
	    $im = <JHEAD>;
	    close(JHEAD);

	    if ($im =~ /^Created:/) {
		if ($tw == 160) {
		    ($w, $h) = (160, 120);
		} else {
		    $pic = $tpath;
		}
	    }
	}

	## ImageMagicky goodness
	unless ($w) {
	    $im = new Image::Magick;
	    $im->Read($pic);
	    ($w, $h) = $im->Get(qw(width height));

	    if ($mode & 011) {	    ## group or other execute bits
		$im->Rotate(degrees => (($mode & 1) ? 90 : -90));
		$im->Scale(width => $tw, height => ($w * $tw / $h));
	    } else {
		$im->Scale(width => $tw, height => ($h * $tw / $w));
	    }
	    unlink($tpath);

	    if ($#$im) {
		$im->[0]->Write($tpath);
	    } else {
		$im->Write($tpath);
	    }

	    ($w, $h) = $im->Get(qw(width height));
	}
    } else {
	($w, $h) = $m->comp('imgsize', $thumb);
    }
</%perl>
<img src="<% $thumb %>" width="<% $w %>" height="<% $h %>" border="0" alt="<% basename($pic) |h %>">\
