Correct compiled order of definitions

This corrects the order of definitions such that variables are always defined immediately before the first function that requires them. 

Also, fixed a unit test.
Not needed since we pop duplicates above