fix a few bugs
reorganize code and fix bug