More code refractoring, many major fixes and improvements