updated recursive version that handles layers betterer