more efficient code and some typos fixed