Implemented saving of user preferences.

Also wrote tests for that, and did some misc. refactoring.