##############################################################################
# Perl Script to convert a Netscape bookmark html file
# into a Windows Favorites directory tree with .URL files for compatibility
# with Microsoft Internet Explorer and quick launch from Windows 95.
# Note: Information about last access time is trashed. Who cares, anyway...
#
# Written by David Binard, 24-Jul-97
# mailto:binard@california.com
#
# History:
# 24-Jul-97     Original
##############################################################################

# Get command-line args.
$Input = $ARGV[0];
shift(@ARGV);
$Output = $ARGV[0];

# Do we have enough args?
if ($Input eq "" | $Output eq "")
{
        Usage();
}

# Open the files
open(IN,"$Input") || die("Unable to open $Input: $!\n");

$path = "";
$_ = $Output;

ProcessDir();

close(IN);

# Usage banner
# Called if user does not provide adequate command-line options
sub Usage {
        print "\n$0: converts a Netscape bookmark html file to a directory tree";
        print "\nwith .URL files for compatibility with Microsoft Internet Explorer";
        print "\nand quick launching from Windows 95.";
        print "\nUsage: ";
        print "perl $0 <html file> <destination directory>\n";
	die("\n");
}

sub ProcessDir {
   CreateDir();
   while(<IN>) {
      if (IsDir()) {
         ProcessDir();
      }
      elsif (IsHyperLink()) {
         CreateShortcut ();
      }
      elsif (IsReturn()) {
         ($path = $path) =~ s/(^.*\\)(.*\\)(\\.*$)?/$1/;
         return;
      }
   }
}

sub IsDir {
      if (/<DT><H3/) {
         return 1;
      }
      else {
         return 0;
      }
}

sub IsHyperLink {
      if (/<DT><A HREF=/ && !/file/) {
         return 1;
      }
      else {
         return 0;
      }
}

sub IsReturn {
      if (/<\/DL><p>/) {
        return 1;
      }
      else {
         return 0;
      } 
}

sub CreateDir {
      (my $dir = $_) =~ s/(^.*?)(<DT><H3.*?>)(.*?)(<\/H3>.*$)/$3/;
      chomp($dir);
      if (! -d "$path$dir") {
         mkdir ("$path$dir", 0777);
      }
      $path = "$path$dir\\";
}

sub CreateShortcut {
      (my $file = $_) =~ s/(^.*>)(.*?)(<\/A>.*$)/$2/;
      chomp($file);
      (my $url = $_) =~ s/(^.*?)(HREF=")(.*?)(".*$)/$3/;
      chomp($url);
      open(SHORTCUT, ">$path$file.url");
      print SHORTCUT "[InternetShortcut]\n";
      print SHORTCUT "URL=$url\n";
      close(SHORTCUT);
}
