Optimized most of the codes, with comments