Try to simplify the part of code which format legend and add a max legend length