Code refactoring

Indentation corrected, TAB characters omitted. To simplify the code some
scoped variables converted to functions parameters.

PS please don't use TAB characters. They have different length in different text editors.