minor refractoring and  bugs fixed