Refactored; fixed some bugs. Still more bugs missing