Modifications to avoid crashes and cleaning up the code