Several code improvements for safety, performance and less redundancy