This could easily be a non-nested function, which would be nicer.