total refactoring of main code, not tested mach yet