THIS NEEDS A LOT OF REFACTORING (and records instead of stupid tuples) but it mostly works like intended...