Reorganized code better and fixed various bugs