Working version. Many improvements to be made