<%init>
use URI;
use URI::Escape ();

# Deal with arguments
my $proto = $ARGS{proto};
my $user  = $ARGS{username};
my $pass  = $ARGS{password};
my $host  = $ARGS{host};
my $port  = $ARGS{port};
my $path  = $ARGS{path};
my $text  = $ARGS{text};
my $query = $ARGS{query};

# Screening Function -- this should expect a reference to the URI object
my $screener = $ARGS{"screen"};

# Go through defaults
if ($host && !$proto)
{
    $proto = "http";
}

if ($host && !$port && $r->get_server_port() != 80)
{
    $port = $r->get_server_port();
}

my $url_string = '';
my $qs;
my $auth;
my @query_string;

# Do some formatting...
if($user && $pass)
{
    $auth = "$user:$pass\@";
}
else
{
    $auth = "";
}

if ($host && $port && $port != 80)
{
    $host = $host . ":" . $port;
}

# The URL string thus far...
if ($host)
{
    $url_string .= "$proto://$auth" . $host;
    $url_string .= '/' unless substr($path, 0, 1) eq '/';
}
$url_string .= $path;

# Deal with a query string, if applicable
if($query)
{
    my $non_escape = '^A-Za-z0-9_';
    while(my($key, $value) = each(%$query)) {
	$key = URI::Escape::uri_escape($key, $non_escape);

	foreach my $v ( UNIVERSAL::isa( $value, 'ARRAY' ) ? @$value : $value )
	{
	    $v = URI::Escape::uri_escape(defined $v ? $v : '', $non_escape);
	    push @query_string, "$key=$v";
	}
    }
}
$qs = join '&', @query_string;
if($qs)
{
    $url_string .= "?$qs";
}

# Did the user submit a screening function?  Call it!
my $uri = URI->new($url_string);

if ($screener)
{
    $screener->($uri);
}

return $uri->canonical;
</%init>
