further refactoring, reduce database calls, especially within functions