We propose a black-box algorithm that generates chemically meaningful Z-matrices and automatically avoids the conditions under which the coordinate transformation between Z-matrices and cartesian coordinates becomes ill-defined. This new algorithm also works in a hybrid way, i.e. the user can define certain internal coordinates and dependencies while the rest of the Z-matrix is automatically constructed. The automatically generated Zmatrices agree with human chemical intuition, have a set of coordinates that simplify the exploration of potential hypersurfaces (PHS) of a molecule, and can be reliably transformed to cartesian coordinates even after structural changes.