Fixes bug 324

Hi Alexey,

Can you take a look at this code? This should fix http://alexeyrybak.com/blitz/bt/view.php?id=324 imo. Not sure if all cases are covered, but this is the most important one imo.

Best,
Nicolas