cleaned up code, separated functions, added z opt