Fix focus on dialog close.
Some refactoring. Move functions etc. in the right place.