working solution, with bug removed