Finalized the script. Thanks to @ommac and @tanismar