Generalize and cleanup the code