Bug fixes and major formatting