added code to properly exit, tweaked to make more efficient