Some messy but functional code