#!/usr/bin/perl -w
use strict;

print("This will convert your Netscape or Mozilla bookmarks to SkipStone's format\nIt will overwrite your current SkipStone bookmarks! so be careful\nIf you want to continue hit Enter, otherwise ctrl-c will exit\n");
if (!@ARGV) { print("No argument value was passed to me!,\nI will attempt to convert netscape's bookmark file\nif you want to convert a different file\n(ie Mozilla) pass it at the command line\n"); }
<STDIN>;
main();

sub main
{
	
	my $file = $ARGV[0] || $ENV{'HOME'}."/.netscape/bookmarks.html";
	open(FILE,"<$file");

	my %root;

	&readns(\*FILE, \%root);

	close(FILE);

	my $i;

	$file = $ENV{'HOME'}."/.skipstone/bookmarks";

	open(FILE,">$file");

	print FILE "folder Menu\n";
#	print "folder Menu\n";
	&printns(\%root);
	print FILE "/folder\n";
	print FILE "folder Toolbar\n";
#	print "/folder\n";
#	print "folder Toolbar\n";
	&printns(\%{$root{sections}[0]}); # i hope...
	print FILE "/folder\n";
#	print "/folder\n";
	close(FILE);
}

sub readns {
    my ($fh, $ref) = @_;
    my $line;
    my $lastRef;

    $ref->{sections} = [];
    $ref->{links}    = [];
    $ref->{sublinks} = 0;

    while ( defined($fh) && ($line = <$fh>) && ($line !~ m!</DL><p>!i) ) {
        $line =~ s/(\r|\n)//g;
        if ($line =~ m!^<H1>(.*?)</H1>$!i) {
            $ref->{name} = 'Root';
            $ref->{url}  = 'index.html';

        } elsif ($line =~ m!<H3 .*?>(.*)</H3>$!i) {
            my $skipping = 0;
            $skipping = 1 if (index($1, '(P)') >= 0); # Private link

            my %sub;
            $sub{url}  = &hashcode($ref->{name}, $1).".html";
            $sub{name} = $1;
            &readns($fh, \%sub);
            if (! $skipping) {
                push @{ $ref->{sections} }, \%sub;
                $ref->{sublinks} += scalar( $sub{sublinks} );
            }

        } elsif ($line =~ m!<DT><A HREF="(.*?)"[^>]*>(.*?)</A>$!i) {
            next if (index($2, '(P)') >= 0); # Private link

            my %url;
            $url{name} = $2;
            $url{url}  = $1;
            $lastRef   = \%url;

            push @{ $ref->{links} }, $lastRef;
            $ref->{sublinks}++;

        } elsif ($line =~ m!<DD>(.*?)$!i) {
            if (defined($lastRef)) { $lastRef->{desc} = $1; }
        }
    }

    return;
}

sub printns {
	my ($ref) = @_;
	my %tree = %{ $ref };
	my $i;	

	for ($i = 0; $i <= $#{$tree{sections}}; $i++) {
		if ($tree{sections}[$i]{name} eq "Personal Toolbar Folder") {
			# do this later
			next;
		}
		print FILE "folder ",$tree{sections}[$i]{name},"\n";
#		print "folder ",$tree{sections}[$i]{name},"\n";
		&printns($tree{sections}[$i]);
		print FILE "/folder\n";
#		print "/folder\n";

	}

	foreach $i (@{ $tree{links} }) {
		print FILE "url ",$i->{url}," ",$i->{name}."\n";
#		print "url ",$i->{url}," ",$i->{name}."\n";
	}

	return;
}

sub hashcode {
	my ($from, $to) = @_;

	my $prefix = lc($from."_".$to);
	$prefix    =~ s/\W//g;

	return $prefix;
}
