Remove duplicated code, correct typing, indentation