KS function + fix some bugs