This code is messy as hell, but it's starting to become something.