refactored and many bugs fixed.