Restructured code to work with arrays