some refactoring/performance tuning
problems 51 and 89