Separated optimize method in many shorter ones

Improved comments and variable names