deal with missing closing boundary

@bf4 @jeremy
Need to extract method and improve readability.