#!/usr/bin/perl

use strict;

my $FVWM = (defined $ENV{FVWM_USERDIR}) ? $ENV{FVWM_USERDIR}
                                        : $ENV{HOME}."/.fvwm";

die ("usage: randombg.pl <directory>") if (! -d $ARGV[0]);

open XASPECT, "-|", "$FVWM/scripts/C/xaspect", "-dimensions";
my $aspect = <XASPECT>;
close XASPECT;
die ("Incompetent use of xaspect") if ($?);

$aspect =~ s/(^\s*)|(\s*$)//g;

opendir WALLPAPER, $ARGV[0];
my @dir = grep(/\Q$aspect\E\.png$/, readdir WALLPAPER);
closedir WALLPAPER;

print $ARGV[0] . "/" . $dir[int(rand(@dir))] . "\n";
