#!/usr/bin/perl

use CGI qw(:standard :cgi-lib);

# Read the standard input (sent by the form):
$FormData = $ENV{'QUERY_STRING'};

# Get the name and value for each form input:
@pairs = split(/&/, $FormData);
# Then for each name/value pair....
foreach $pair (@pairs) {
    # Separate the name and value:
    ($name, $value) = split(/=/, $pair);
    # Convert + signs to spaces:
    $value =~ tr/+/ /;
    # Convert hex pairs (%HH) to ASCII characters:
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    # Store values in a hash called %FORM:
    $FORM{$name} = $value;
}


$path = '/mit/course-search/web_scripts/search/urls/save/';

foreach $num (keys(%FORM)){
    $file = $path . $num;
    $file =~ tr/A-Z/a-z/;
    @text = split(/ /, $FORM{$num});
    $url = $text[1];
    unlink($file);
    open(FILE, "> $file");
    print FILE $url;
    close(FILE);
    redirect($url);
}

sub redirect
{
    local($location) = @_;

    print header("-status"=>"301 Moved Permanently",
		 "-location"=>$location);
    print start_html;
    print p("You should be automatically redirected to the course site in a moment.  If you are not redirected,",
	    a({"href"=>$location}, "click here."),
	    "\n");
    print end_html, "\n";
    
}
