In some places i switched from an if/else to a match to avoid calling size twice. I took that from looking at your code.