Algin your method to the top of your screen. Now scroll one more line down. According to your algorithm, it's now impossible to know which line belongs to which scope.
I have a different algorithm:
- Find first indented line
- Find next unindented line
If that does not work for you, your code is bad.