Fixes and refactorings

May need some rephrasing but this should make it work.