restructured, commented for clarity