Added some comments and improved some error handlings.