Not the most compact or elegant. Learning in progress.