Rewritten to use functions, query updated to a 'join'