New version: refactored by alexeykuzmin