Refactor depth calculation to a separate function