Moved code arround, fixing some defects