Add changes made by Alexey Pavlov (big thanks to him).