<%perl>
    my ($path) = @_;
    my ($base, $fbase, $w, $h, $file, $vpath, $vfpath, $im, $mode, $vw, $t);

    $vw = $m->comp('config')->{view_width};
    ($w, $h) = $m->comp('imgsize', $path);

    $base = $m->top_comp->dir_path;
    $fbase = $m->top_comp->source_dir;

    $path =~ s|^$base/||;
    $vpath = "$base/gallery/tmp/view/$path";
    $vpath =~ s/\.(gif|png)$/.jpg/;
    $vfpath = "$fbase/gallery/tmp/view/$path";
    $vfpath =~ s/\.(gif|png)$/.jpg/;
    $path = "$fbase/$path";

    ($mode,$t) = (stat($path))[2,9];
    if ($w > $vw || $mode & 011) {
	unless (-e $vfpath && $t < (stat($vfpath))[9]) {
	    mkpath([dirname($vfpath)], 0, 0777) unless -d dirname($vfpath);
	    $im = new Image::Magick;
	    $im->Read($path);

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

	    unlink($vfpath);

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

	    ($w, $h) = $im->Get(qw(width height));
	}

	($w, $h) = $m->comp('imgsize', $vpath);
	return($vpath, $w, $h);
    } else {
	return(basename($path), $w, $h);
    }
</%perl>
