Improved more robust & testable version.