split into files and wrote top level functions. need to test and debug.