implemented working algorithm