Merged and added code from older merge using swarage's code