To continue the theme started in previous post.
I have tested this algorithm in different cases and it works. And rotation in DPP is not a problem.
I'm not programmer and this BAT file (for Windows) may be not fine, but it works. I've wrote some remarks in the text.