optimization + minor bugs