Refactor script

Make script more robust and easier to read. Functionality and usage remain
unchanged.