Cleaned up tree code