Added shebang, use of writeToLog and code tidyup