#!/usr/bin/perl

#
# Common usage: ./bookmarks2js.pl < bookmarks.html > bookmarks.js
#
use strict;
use utf8;

my ($level, $tree) = (0, 0);
my @subtree = ("foldersTree");

print <<EOF;
USETEXTLINKS = 1
$subtree[0] = gFld("<i>Bookmarks for Dmitry</i>", "./bookmarks/bookmarks.html")
EOF

sub convert
{
	$_ = @_[0];
	s/\r\n?//g;
	return $_;
}

binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";

while (<>)
{
	if (/<DT><H3[^>]*?>(.*?)<\/H3>/)
	{
		$tree++;
		print "tree$tree = insFld($subtree[$level], gFld(\"" . convert($1) . "\"))\n";
		$subtree[++$level] = "tree$tree";
	}
	elsif (/<DT><A HREF="(.*?)".*?>(.*?)<\/A>/)
	{
		my ($href, $desc, $redo) = ($1, convert($2), 1);
		$_ = <>;
		if (/<DD>(.*)$/)
		{
			$desc .= " (" . convert($1) . ")";
			$redo = 0;
		}
		print "insDoc($subtree[$level], gLnk(1, \"$desc\", \"$href\"))\n";
		redo if $redo;
	}
	elsif (/<\/DL>/)
	{
		$level--;
	}
}
