simplified code a bit more, added some clearer comments