Function really needs tidying up, but it's functional and working!