New code: Based on Mahdi-Rom

All new code, copy pasted to fix any build errors.