Implemented working algorithm (bad performance)