slightly better algorithm maybe