Previous attempt - f226c3eb0c. Approach introduced in this commit is theoretically much better, but it still might not be perfect.
f226c3eb0c