fix newline bug and make region code robust