introduced clamp flag to shape cost function
changed optimization to rely on the distance map of the mask