Extracted all the logic to a shell script. Fixed some slight errors.