#!/usr/bin/perl -w
#
# opml2mdwn.pl 
#
# This script evolved from:
#
# opml2html.pl, (c) Jeremy Zawodny -- http://jerermy.zawodny.com/blog/
#
# You may distribute this code freely.  It's not rocket science.
#
# Given an OPML file on stdin, produces an MDWN - Output of the Feedlist.
#
# Usage: opml2html.pl < foo.opml > bar.mdwn
#

use strict;      # ---- barfs out *grrr

use warnings;
use XML::Simple;
use XML::OPML;
use Data::Dumper;
use HTML::Entities;

my $xml;

{
    local($/) = undef;
    $xml = <>;
}

my $info = XML::Simple::XMLin($xml,KeyAttr=>"outline",ForceArray=>1);

print "# Feedlist \n\n\n\n";

?MyIterate($info->{body}[0]->{outline},0,5);
        
sub ?MyIterate
        {
        my $obj=shift;
        my $depth=shift;
        my $maxlevel=shift;
        
        if ( $maxlevel < 0) {return}

        my $path="";
        if ($depth>0) 
                {
                for (my $i=0; $i<$depth;$i++)
                        {
                        $path.=" ";
                        }
                }

        for my $o (@{$obj})
                {
                my $title = $o->{title};
                my $h_url = $o->{htmlurl} || $o->{htmlUrl};
                my $x_url = $o->{xmlurl}  || $o->{xmlUrl};
                my $descr = encode_entities($o->{description});
            print "\n";
            if (
                        ("" ne $title)
                &&      ("" ne $h_url)
                &&      ("" ne $x_url)
                &&      ("" ne $descr)
                )
                {
                print "$path* ";
                        print "[\\[\\]]($h_url) $title [ (Feed) ]($x_url)";
                        print "\n$descr\n" if ( $descr ne $title );
                        } else {
                        print "\n$title";
                        }
                
                ?MyIterate($o->{outline},$depth+1, $maxlevel-1);
                }
                
        }