Autodetect branch

The last commit in this PR is a cosmetic/semantic fix that I noticed too late. I'll rebase it into the first commit before pushing to master.