Fixed a loop invariant bug & a casting bug