Add logging and extract common code
Replace System.err with logging
Extract common code. Fix test.