Optimal conditions for Bell-inequality violation in the presence of decoherence and errors