Restructured TS map computation

As close to final as it could get today.
These imports should go at the top of the file.