first implementation, based on pseudocode from wikipedia
fixed issue of generating the WRONG a everytime due to faulty logic