Several reference counting fixes that were badly affecting memory use
Style cleanup and Slightly better error handling too.