working algorithm, removed state class