Rewrite setup script

Rebased the #412 PR on the `dev` branch