reorganized code, added some comments