slightly better algorithm