cleaned and improved code; added helper functions