if I get the WiFi.begin(ssid, password) back to the setup() its all OK.That is because it belongs in setup!
At the start of the script includes, constants and functions are being declared. The work of the script commences in setup. Setup does what it says, sets things up ready for the main programme.