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

# Small utility to parse Opera bookmark files.
# Originally written in Python by Lars Marius Garshol
# perl version - Briac Pilpré
# modified version to select a given subfolder and
# recreate a bookmark file - Marc Baaden
# (comments for the latter to baaden@smplinux.de)

my $folder = shift @ARGV;
my $title  = shift @ARGV;

my $version = <>;
die "Doesn't seem to be a Opera Hotlist\n" if $version !~ /^Opera/;

chomp( $version );

my $tmp;
my $flag=0;

while (<>){
        next unless /\S/;
        chomp;
        if ( $_ eq '#FOLDER' ){
                my $node = $_;

                my $line;
                {
                        local $/ = "";  # Paragraph mode
                        $line    = <>;
                }

  $tmp = $line;
                my $name    = $1 if $line =~ /NAME=(.*)/;
                my $created = $1 if $line =~ /CREATED=(.*)/;
                if ( $name eq $folder ) {
#                  print "Opera Hotlist version 2.0
                  print "$title
Options: encoding = utf8, version=3

#FOLDER
";
                  print $tmp;
                  $flag = 1;
                  last;
          }

}
}

if ($flag == 0) {die "Folder  >> $folder <<  not found."};

my $folder_count=1;

while (<>){
        next unless /\S/;
        chomp;
        if ( $_ eq '#FOLDER' || $_ eq '#URL' ){
                my $node = $_;

                my $line;
                {
                        local $/ = "";  # Paragraph mode
                        $line    = <>;
                }

                if ($node eq '#FOLDER'){
                  $folder_count++;
                  print $node."\n";
                        print $line;
                }

                elsif ($node eq '#URL') {
                  print $node."\n";
                        print $line;
                }

        } elsif ( $_ eq '-'){
                print $_."\n\n";
                  $folder_count--;
                if ($folder_count == 0) { last };
        }
}
