improved legend code