Completed script; See header comments for details