first apparently working code, needs more testing