implemented way better algorithm