[api] move do_branch function into it's own class

and split the big function into several smaller ones