Refactor a lot of things to make PM handling work