Code rewritten - mostly