$keywordsDir = "u:/keywords";
$baseMatDir = "u:/hl2/hl2/materials";

use Win32::Shortcut;

sub ResolveShortcut
{
	local( $shortcut ) = shift;
	local( $link ) = Win32::Shortcut->new( $shortcut );
	return $link->{'Path'};
}

sub CreateShortcut
{
	local( $shortcutname ) = shift;
	local( $fileToPointAt ) = shift;

	local( $link ) = new Win32::Shortcut();

	if( $link ) 
	{
		$link->Path( $fileToPointAt );
		$result=$link->Save( $shortcutname );
		if( !$result )
		{
			print "*** ERROR *** Creating shortcut $shortcutname pointing at $fileToPointAt\n";
		}

		$link->Close(); 
	} 
	else 
	{
		print "*** ERROR *** Creating shortcut $shortcutname pointing at $fileToPointAt\n";
	}
}


sub BackSlashToForwardSlash
{
	local( $in ) = shift;
	local( $out ) = $in;
	$out =~ s,\\,/,g;
	return $out;
}

sub MakeDirHier
{
	local( $in ) = shift;
#	print "MakeDirHier( $in )\n";
	$in = &BackSlashToForwardSlash( $in );
	local( @path );
	while( $in =~ m,/, ) # while $in still has a slash
	{
		local( $end ) = &RemovePath( $in );
		push @path, $end;
#		print $in . "\n";
		$in = &RemoveFileName( $in );
	}
	local( $i );
	local( $numelems ) = scalar( @path );
	local( $curpath );
	for( $i = $numelems - 1; $i >= 0; $i-- )
	{
		$curpath .= "/" . $path[$i];
		local( $dir ) = $in . $curpath;
#		print "mkdir $dir\n";
		mkdir $dir, 0777;
	}
}

sub RemoveFileName
{
	local( $in ) = shift;
	$in = &BackSlashToForwardSlash( $in );
	$in =~ s,/[^/]*$,,;
	return $in;
}

sub RemovePath
{
	local( $in ) = shift;
	$in = &BackSlashToForwardSlash( $in );
	$in =~ s,^(.*)/([^/]*)$,$2,;
	return $in;
}

sub ProcessVMTFile
{
	local( $vmtname ) = shift;

#	print "$vmtname\n";
	local( @keywords );
	local( *VMT );
	open VMT, "<$vmtname";
	local( $line );
	while( $line = <VMT> )
	{
		$line =~ s/materialset/keywords/ig;
		if( $line =~ m/^\s*\$keywords\s*=\s*\"(.*)\"/gi )
		{
			push @keywords, split ",", $1;
		}
	}
	close VMT;
	local( $keyword );
	foreach $keyword( @keywords )
	{
		&MakeDirHier( $keywordsDir . "/" . $keyword );
		local( $shortcutname ) = $keywordsDir . "/" . $keyword . "/" . 
								 "Shortcut to " . &RemovePath( $vmtname ) . ".lnk";
		&CreateShortcut( $shortcutname, $vmtname );
	}
}

sub ProcessFile
{
	local( $filename ) = shift;
#	print "$filename\n";
	if( $filename =~ /\.vmt/i )
	{
		&ProcessVMTFile( $filename );
	}
}

sub ProcessFileOrDirectory
{
	local( $name ) = shift;

#	If the file has "." at the end, skip it.
	if( $name eq "." || $name eq ".." || $name =~ /\.$/ )
	{
		return;
	}

#   Figure out if it's a file or a directory.
	if( -d $name )
	{
		local( *SRCDIR );
#		print "$name is a directory\n";
		opendir SRCDIR, $name;
		local( @dir ) = readdir SRCDIR;
		closedir SRCDIR;

		local( $item );
		while( $item = shift @dir )
		{
			&ProcessFileOrDirectory( $name . "/" . $item );
		}
	}
	elsif( -f $name )
	{
		&ProcessFile( $name );
	}
	else
	{
		print "$name is neither a file or a directory\n";
	}
}

&ProcessFileOrDirectory( $baseMatDir );




