rewrote calc_optimal_width_and_height function