First commit primarily based on nikita2206's work, with a few customized changes