Working copy, needs further debugging and cleanup