this patch make some changes, but it is not clear why exactly? There are some simple fixes, but also some bigger rewrites. Please can you split that into smaller patches, and add a reasonable commit message to each change?