A General Algorithm for Word Graph Decomposition