Cleanup and refactor

I did a lot, so please check things thoroughly.