restructured some state changes, other tiny changes, potentially introduced new bugs. Needs testing