Big update. Most functions rewritten.