added depth tracking to flatten.