func reverseAnimation(anim : CAAnimation, totalDuration : CFTimeInterval) -> CAAnimation{
var duration :CFTimeInterval = anim.duration + (anim.autoreverses ? anim.duration : 0)
if anim.repeatCount > 1 {
duration *= CFTimeInterval(anim.repeatCount)
}
let endTime = anim.beginTime + duration
let reverseStartTime = totalDuration - endTime

var newAnim : CAAnimation!

//Reverse timing function closure
let reverseTimingFunction =
{
(theAnim:CAAnimation) -> Void  in
let timingFunction = theAnim.timingFunction;
if timingFunction != nil{
var first : [Float] = [0,0]
var second : [Float] = [0,0]
timingFunction?.getControlPoint(at: 1, values: &first)
timingFunction?.getControlPoint(at: 2, values: &second)

theAnim.timingFunction = CAMediaTimingFunction(controlPoints: 1-second[0], 1-second[1], 1-first[0], 1-first[1])
}
}

//Reverse animation values appropriately
if let basicAnim = anim as? CABasicAnimation{
if !anim.autoreverses{
let fromValue: Any! = basicAnim.toValue
basicAnim.toValue = basicAnim.fromValue
basicAnim.fromValue = fromValue
reverseTimingFunction(basicAnim)
}
basicAnim.beginTime = CFTimeInterval(reverseStartTime)


if reverseStartTime > 0 {
let groupAnim = CAAnimationGroup()
groupAnim.animations = [basicAnim]
groupAnim.duration = maxDuration(ofAnimations: groupAnim.animations! as [CAAnimation])
for anim in groupAnim.animations!{
anim.fillMode = .both
}
newAnim = groupAnim
}
else{
newAnim = basicAnim
}

}
else if let keyAnim = anim as? CAKeyframeAnimation{
if !anim.autoreverses{
let values : [Any] = (keyAnim.values?.reversed())!
keyAnim.values = values;
reverseTimingFunction(keyAnim)
}
keyAnim.beginTime = CFTimeInterval(reverseStartTime)

if reverseStartTime > 0 {
let groupAnim = CAAnimationGroup()
groupAnim.animations = [keyAnim]
groupAnim.duration = maxDuration(ofAnimations: groupAnim.animations! as [CAAnimation])
for anim in groupAnim.animations!{
anim.fillMode = .both
}
newAnim = groupAnim
}else{
newAnim = keyAnim
}
}
else if let groupAnim = anim as? CAAnimationGroup{
var newSubAnims : [CAAnimation] = []
for subAnim in groupAnim.animations! as [CAAnimation] {
let newSubAnim = reverseAnimation(anim: subAnim, totalDuration: totalDuration)
newSubAnims.append(newSubAnim)
}

groupAnim.animations = newSubAnims
for anim in groupAnim.animations!{
anim.fillMode = .both
}
groupAnim.duration = maxDuration(ofAnimations: newSubAnims)
newAnim = groupAnim
}else{
newAnim = anim
}
return newAnim
}
