Restructured code, fixed duplicate variable name issue