On first glance there seems to be a lot of duplicate code. I'll try to refactor it a bit in the evening (UTC).