You could use ShiftScale filter to achieve W/L transformation. Then search for parameters which get you close to the desired result. Before attempting to write any code, I suggest you use 3D Slicer to experiment, both to see whether this would work at all, and if so what would be a good window and level.