I don't like this code very much. Probably should be cleaned up separately though.