LPS-41267 fix trash bugs and improve code extracting common logic

@zsoltbalogh the first 3 commits should be backported (only those 3)