This is mainly copy-pasted from the old version with some changes, I plan on doing a full review of it and possible refactor once we know that it works.