minor modification and cleaning up before packaging into functions