Fix some errors, simplify the code a bit