general fixes and issues related to PR #124 and #125. Also adds code refactoring