search and replace fixed length record file

Hi

I need to be search a file of fixed length records and when I hit a particular record that match a search string, substitute a known position field

In the example file below

FHEAD000000000120090806143011
THEAD0000000002Y0000000012 P00000000000000001234
TTAIL0000000003
THEAD0000000004Y0000000044 N00000000000000001299
TTAIL0000000005

I need to only consider the THEAD records and swap the Ps to Ns, and visa versa, in position 40,

Thanks in advance