Try two: Port all build system changes from master to template branch

#41, but with a squashed fix for #40. Doing this in another PR because I wanted to keep the original branch from #41 for comparison.