cleaned up messy aggregate function