implementing depth sorting