My version of program, described at the start of http://habrahabr.ru/post/197926/ topic