Algorithm(?) from ZokumBSP: https://github.com/zokum-no/zokumbsp/blob/22af6defeb84ce836e0b184d6be5e80f127d9451/src/zokumbsp/preprocess.cpp#L561-L650