fixes use of globals, unnests functions