Document code thoroughly and refactor for readability