moved a bunch of code around for better testabality/separation