optimization and small bug fixes