added some structure and code reorganized
safer use of trim
safer use of trim