Refractoring code, and minor improvements