Made some functions local, moved some code