Sort of working algorithm