I see that this function has lots of code duplication. Example L49-61 and L65-77
Could you think of the way to dehydrate your code. Either refactor the code or create a function with meaningful name which will indicate what it is for as well as used for those code blocks instead.