Cleaned up, refactored to optimise a number of features and added API facility via the fmt=json GET parameter