major code tidyup, small functionality improvement