Fix SQL, remove redundant code, minor bugfixes