complicated lock handling, fixes #227