Put code into functions. Fix var names