App Reel

Pending algorithm: I could calculate number of brackets () before each WHERE and if it zero - I found correct WHERE position. Could anybody propose me a simpler algorithm or simple implementation on Java my one?