working code, most probably finished