Config rewrite

This includes all the other fixes I've done, so this is a complete package (please drop the previous pull request).

For my simple tests, everything seems to work.