Finished code; added some optimization;