#!/usr/bin/env python
import urllib
import sys

def fetchRSS( rss ):
    """Download's the feed and returns the temp name"""
    tempfilename = '/tmp/.rss-hack'
    tempfile = open("%s-2" % tempfilename,'w+') # better later on

    conn = urllib.urlopen( rss )
    while 1:
        s = conn.read(2)
        if not s:
            break
        tempfile.write( s )
    conn.close()
    tempfile.close()
    # fix for some problems with for exampel the rss from the register (my fault)
    tempfile = open("%s-2" % tempfilename)
    tempdata = tempfile.readlines()
    tempfile.close()
    tempfile = open(tempfilename, 'w+')
    for row in tempdata:
        row = row.replace('</link>','</link>\n').replace('</title>','</title>\n').replace('</description>','</description>\n')
        tempfile.write( row )
    tempfile.close()
    return tempfilename

def praseRSS( rssfile ):
    """Prase an rss file (or extract the title and link, description and return them as a list)"""
    tempfile = open(rssfile,'r')
    templist = tempfile.readlines()
    tempfile.close()

    titles = list()
    links = list()
    description = list()

    def cutterMan(string, startTag, endTag, grepStart, grepEnd, offset = 0):
        """Cut's away nastiness and cleans my code"""
        start = string.find( startTag )
        stop = string.find( endTag )
        string = string.strip()[start:stop]
        
        start = string.find( grepStart ) + offset
        stop = string.find( grepEnd )
        string = string.strip()[start:stop]
        return string
    
    for temp in templist:
        if temp.find('<title>') != -1:
            titles.append( cutterMan(temp, '<title>', '</title>', 'e>', '</', 2) )

        if temp.find('<link>') != -1:
            links.append( cutterMan(temp, '<link>', '</link>', 'http://', '</' ) )

        if temp.find('<description>') != -1:
            description.append( cutterMan(temp, '<description>', '</description>', 'ion>', '</', 4) )
            
    output = [ titles, links, description ]
    return output

def filterRSS( rss ):
    """Removes uglies (in an uglie faschion)"""
    for x in range(0, len( rss ) -1):
        rss[x].__delitem__(0)
        rss[x].__delitem__(0)
    # for description
    rss[2].__delitem__( len( rss[2] ) -1 )
    rss[2].__delitem__(0)
    return rss

def outputRSS( rss, showdesc ):
    """Formats and Prints out the rss"""
    for x in range(0, len( rss[0] ) -1 ):
        sys.stdout.write( "%i: %s:\n\t%s\n" % ( x, rss[0][x], rss[1][x] ) )
        if showdesc == True:
            if len( rss[2][x] ) < 65:
                maxwidth = len( rss[2][x] ) -1
            else:
                maxwidth = 65
            sys.stdout.write( "\t\"%s...\"\n" % ( rss[2][x][:maxwidth] ) )
            
# main
# syntax:
#    rss-hack.py [-d] [rss]
rss = "http://slashdot.org/slashdot.rss"
showdesc = False

if len( sys.argv ) != 1 and sys.argv[1] != '-d':
    rss = sys.argv[1]
elif len( sys.argv ) != 1:
    if sys.argv[1] == '-d':
        showdesc = True
        if len( sys.argv ) != 2:
            rss = sys.argv[2]

rssfile = fetchRSS( rss )
rss = praseRSS( rssfile )
rss = filterRSS( rss )
outputRSS( rss, showdesc )
