Restructured code for clarity and speed