It has to iterate over all layers and do string comparison to find the index back. Instead we just keep track of the index so this should improve performance a bit.
Instead of making lots of nested if statements, use the if statements as an interruption check. This reduces the indentation a lot and makes it easier to read in my opinion. It also makes it easier to add stuff to these checks.