More fixes

Getting closer to what I want. The code is becoming more structured, more robust and hopefully easier to maintain.