Con la funzione che ti ho postato, avresti evitato almeno la metà di codice