Code clean up and #define and checks for some errors