[tpwd] Make the code more readable, fix a few minor bugs