Several fixes
Added ability to run as script (for testing).