There are some bugs, but this is the best I could do. Credit to @paulinfinity for the suggestion to make it faster :)