Turned the devices.php code inside-out and made spaghetti code into lasagna. Much tastier and easier to debug.