Avoiding UB and some fixes