Multiple fixes and code refactoring

Multiple bug fixes and code refactoring (main in the main script)