added shebang, refactored a little to save memory