drop duplicated code and add more nicer macros, clean-up some code that could lead to segfaults