Various logic fixes and style clean up.