write a working solution [not too beautiful though]