I've just been trying to use math all this time.
Here is the script for a proof of concept cube I wrote.
it only works some of the time
edit: After tinkering with this a little bit more (with a version with less mistakes than what I've posted here), it seems the mistake I made was trying to do this with a few lines of code.