Fix logic problem and some compilation problems