Main functionality in. Lightly tested