readability improvement and minor bugfixes, but still acting slightly incorrect