Major code refactor. still a few bugs but almost done