code optimization and some fixes