Keep buffer after ctrl command.
Remove superfluous code.
Use associative arrays to keep matched lines.

Also get rid of duplicate lines.