#!/usr/bin/ruby -d
require 'open-uri'
# Enter proxy in form of 'http://URL:PORT', set to nil if proxy unneeded
PROXY = 'http://195.175.37.6:8080'
#PROXY = nil
concert_savefile = IO.read("concerts.data")
$new_concerts =""
begin
# get count
open("http://www.radioswisspop.ch/nav/main_header.php?title=Konzertkalender:%20_%20Veranstaltungen&lang=de8",
        { :proxy => PROXY}) do |counter|
                counter.read =~ /<h1>Konzertkalender: (.*?) Veranstaltungen<\/h1>/
                $count = Integer($1)
        end
rescue Exception => detail
        puts "ERROR (#{detail.class.name} - #{detail.backtrace})"
end

begin
concert_date = "Heute" #def concert_date to use globally instead of only in block
new_concerts = []
File.open(".old_concerts") do |f|
        $old_concerts = Marshal.load(f)
end
all_concerts = []
1.step($count ,100) {|listfrom|
        open("http://www.radioswisspop.ch/cgi-bin/events/list.cgi?start=#{listfrom}&lang=de&prg=p",     { :proxy => PROXY }) do |website|
                # Parse linewise
                website.each do |line|
                        line =~ /<td colspan=4><br><b>(.*?)<\/b>/
                        if !$1.nil? then
                                concert_date = $1
                        end
                                                line =~ /javascript:sl(.*?)>(.*?)</     # $2 = Location
                                next if $2.nil?
                        concert_location = $2.strip unless $2.nil?
                        line =~ /javascript:sc(.*?)>(.*?)</     # $2 = Ort
                        concert_city = $2.strip unless $2.nil?
                        line =~ /javascript:oe(.*?)<b>(.*?)</   # $2 = Artist
                        concert_artist = $2.strip unless $2.nil?
                        concert = " Wer: #{concert_artist}\n Wann: #{concert_date}\n Wo: #{concert_city} (#{concert_location})\n\n"
                        concert = concert.gsub(/&auml;/,'ä').gsub(/&uuml;/,'ü').gsub(/&ouml;/,'ö')
                        all_concerts.push(concert)
                        if !$old_concerts.include? concert and !concert.nil? then
                                new_concerts.push(concert)
                        end
                end
        end     
}
rescue Exception => detail
        puts "ERROR (#{detail.class.name}: #$! - #{detail.backtrace})"
end
File.open(".old_concerts", File::CREAT|File::TRUNC|File::WRONLY) do |f|
        Marshal.dump(all_concerts,f)
end
f = File.open(".new_concerts", File::CREAT|File::TRUNC|File::WRONLY)
f.puts(new_concerts)
f.close
`mutt -s "Neue Konzerte" ec@nihil.ch < .new_concerts` if !new_concerts.empty?