Restructuring, small bug fixes