refactored really ugly code