commited complete rewrite in C