Restructured code, removed code duplication