#!/usr/bin/env perl

use strict;

while(<STDIN>)
{
	chomp;
	my @fields = split("\t");
	unless(@fields == 3)
	{
		print STDERR "Bad line: $_\n";
		next;
	}
	my ($spell, $file, $url) = @fields;
	unless($spell =~ m:^([^\s/]+)/([^\s/]+)$:)
	{
		print STDERR "Strange spell: $spell\n";
		next;
	}
	my $dir = $1;
	mkdir($dir) unless -e $dir;
	my @urlentries;
	my $urlfile = "$dir/urls.txt";
	if(-e $urlfile)
	{
		open(my $ufh, '<', $urlfile)
			or die "Cannot open $urlfile! ($!)\n";
		@urlentries = <$ufh>;
	}
	my $urlline = "$file\t$url\n";
	unless(grep {$_ eq $urlline} @urlentries)
	{
		open(my $ufh, '>>', $urlfile);
		print $ufh $urlline;
	}
}
