attempt to convert most of this mess into something which at least look like C code