It seems to me like these two if blocks are duplicating a lot of functionality.