Refactored a bit, cleaned up code, see notes on previous commit