some optimize and fixes in code