First version, based on my old code. It can be ugly