This needs to be rewritten badly.