Minor rewrite of most of the code