Rewrote substantially per yorick's and ImBcmDth's coding suggestions