turning tidied up and low level functions moved to io.cpp