Directed and elliptic flow of charged pions and protons in Pb + Pb collisions at 40A and 158A GeV