Fix bugs, simplify SQL, and improve the code layout in line with the guidelines