Re-integrated with TJ's code because I accidentally overwrote it.