Code completly rewritten