slightly rewrote it, might be a bit faster