Bug fixes for #38, #39, #40