reorganize code, add comments