final working copy, solved on CodeEval