moved code around a bit to increase modularity