Code refactored based on Vitaly Litvak idea