Revised code for efficiency and readability

I made many of the suggested changes by Ryan but some are missing, will
post as issues.