Fixed bug and algorithm