I guess it should be:

    val + w > wmax ? wmax - w : val