Improved the flatten function to take a number of nesting levels it will flatten.