Some code improvements and bug solving