Refactored 'wait_til_state' function to simplify it.
Made 'max_tries' configurable.