Heavy refactoring to speed things up, reduce number of queries.