Save and restore window state and geometry

and a few more refactoring