code re-organization for z_ends

added comments and indentation, removed unused variables