fixing depth bug and placed all the checks up front in flatten instead of sprinkled all over the code