Main function code done

Need more test.