Any suggestions on simplifying this script? It works nicely but doesn't look very elegant.