Fix for #116

Includes aggressive refactoring. I'll completely understand if you reject this PR because of that.
That said I'm pretty satisfied with the result, I'd be happy if you would merge this.