Why set PORTx before TRISx?
The PORTx bits are adjusted before the TRISx bits so you know what the output will be before you make the pin an output. If you are setting the TRISx bits to inputs, it doesn't matter. However, if you are clearing the TRISx bits and making them outputs, it is safer to determine what the output will be before it switches from input to output. Thus, if an alarm or something goes off when a pin is high, you would want to make sure when it becomes an output, it starts off low.