readability and comments slightly changed