updated to be more modular.  separate functions for each portion of functionality