Simplified code and fixed a critical bug