Rewritten code as suggested in comments