Revised code with dfoster, made more changes, and some fixes.