worked on CRM-12463 restructured code and fixes
Merge pull request #588 from kurund/CRM-12463

worked on CRM-12463 restructured code and fixes