#!/usr/local/bin/perl
# Perl source code for urldecoding strings
# urlencoded string: varname1=value1&varname2=value2...
#   spaces are encoded (sometimes) as "+"s
#   some characters (inc. punctuation, \n, \t) are encoded by hex code
#      e.g. name1=Greg%20Smith%0a is "Greg Smith\n"

# global variables--easier than trying to return arrays
@VarNames=();
%VarValues=();

# $number = &DecodeUrl($string)
sub DecodeUrl
{
    local($str) = $_[0]; # don't modify original string
    local(@entries,$val);

    %VarValues=(); @VarNames=(); # clear any old values
    @entries = split("&",$str); # split into entries

    #print STDOUT "Num = ",$#entries,"\n";

    # go through each entry, split into varname and value, remove
    # +'s and hex codes
    for (local($i)=0;$i<=$#entries;$i++)
    {
        #print STDOUT 'entry=',$entries[$i],"\n";

        # split into name and value
        ($VarNames[$i],$val) = split("=",$entries[$i]);

        #print STDOUT "name=",$names[$i]," val=",$val,"\n";

        $val =~ s/\+/ /g; # replace +'s with spaces
        # this is why we love perl--replace hex codes w/ ascii char
        # there's probably a better way to do this, but this seems to
        # work pretty well.
        1 while $val =~
            s/(.*)%([\da-fA-F]{2})(.*)/$val=sprintf("%s%c%s",$1,hex($2),$3)/eg;
	# get rid of ^M's
	$val =~ s/\r//g;
        $VarValues{$VarNames[$i]} = $val;

        #print STDOUT "-----------\n";
    }
    $i; # return the number of entries (not the highest index)
}

# $number = &GetNumVars($string);
sub GetNumVars
{
    local($str) = $_[0]; # don't modify original string
    local(@temp);
    @temp = split("&",$str); # split around &'s, into entries
    $#temp + 1; # returns the number elements in $temp
}

