Adopted the solution by Dmitry Vyukov