fix #104, better algorithm