Ported and improved CMake macros from next branch