Fix declaration and logic errors. Some style cleanup by akling.