added helper function; reorganized code