Re-adopted Matthias's solid method, made a minor tweak to make it a little better, but it's still buggy.