Not refactored working algorithm