refactorized code and added queue function