Added port argument and templated output
Modularized, future-proofed, and better error handling