code cleaning and some small bugs