improved code structure significantly, fixed various bugs