Reorganize, fix bug in code