Bug fix and reorganized code