translated and refactored up to line 3573