NOTE: In some places indention is not updated to keep this patch readable. This will be fixed in the next revision.