wrote bulk of function