An algebro-geometric approach to S-duality and T-duality and proof of modularity conjectures in BPS counting theories