added the legends and fixed bugs.