added safe printing, cleaned up code