Moving some stuff from shell script in here, and some refactoring.