fix #95, better algorithm