I found some inconsistencies in my patch so here's the fixed version.