<file_sep>//
//  SavedEvents+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 8/9/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(SavedEvents)
public class SavedEvents: NSManagedObject {

}
<file_sep>//
//  MyNewTeachers+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 1/6/19.
//  Copyright © 2019 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension MyNewTeachers {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<MyNewTeachers> {
        return NSFetchRequest<MyNewTeachers>(entityName: "MyNewTeachers")
    }

    @NSManaged public var first: String?
    @NSManaged public var last: String?
    @NSManaged public var subject1: String?
    @NSManaged public var subject2: String?
    @NSManaged public var isFemale: Bool
    @NSManaged public var schedule: NSSet?

}

// MARK: Generated accessors for schedule
extension MyNewTeachers {

    @objc(addScheduleObject:)
    @NSManaged public func addToSchedule(_ value: MySchedule)

    @objc(removeScheduleObject:)
    @NSManaged public func removeFromSchedule(_ value: MySchedule)

    @objc(addSchedule:)
    @NSManaged public func addToSchedule(_ values: NSSet)

    @objc(removeSchedule:)
    @NSManaged public func removeFromSchedule(_ values: NSSet)

}
<file_sep>//
//  NewsDetailViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/30/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import SDWebImage

class NewsDetailViewController: UIViewController {

    @IBAction func actionTapped(_ sender: Any) {
        let ac = UIActivityViewController(activityItems: [storyURL!], applicationActivities: [])
        present(ac, animated: true)
        
    }
    @IBAction func dismiss(_ sender: Any) {
        navigationController?.popViewController(animated: true)
    }
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var newsTitle: UILabel!
    @IBOutlet weak var newsInfo: UILabel!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var content: UILabel!
    
    
    var titleText = String()
    var info = String()
    var imageLink: URL?
    var news = String()
    var storyLink = String()
    var storyURL: URL?
    
    override func viewDidLoad() {
    
        super.viewDidLoad()
        storyURL = URL(string: storyLink)
        navigationBar.my_setNavigationBar()
        newsTitle.text = titleText.uppercased()
        newsInfo.text = info.uppercased()
        imageView.sd_setImage(with: imageLink, placeholderImage: UIImage(named: "newsPlaceholder"))
        let newsFix = news.replacingOccurrences(of: "<p>", with: "<br><p>")
        let attributedText = try! NSAttributedString(data: newsFix.data(using: .unicode, allowLossyConversion: true)!, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil)
  
        content.text = attributedText.string
        
//        let attributedString = NSMutableAttributedString(string: content.text!)
//        let attributes: [NSAttributedStringKey: Any] = [.font: UIFont(name: "Lato-Regular", size: CGFloat(18).relativeToWidth), .foregroundColor: UIColor.blue]
//
//        attributedString.addAttributes(attributes, range: NSRange(location: 0, length: 1))
//        content.attributedText = attributedString
       
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  my_glowAnimation.swift
//  PHS App
//
//  Created by <NAME> on 8/22/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit

extension UIView {
    func my_glow() {
       
        let size = layer.frame.size.height
        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.white.cgColor
        self.layer.shadowOffset = CGSize(width: size * 0.24, height: size * 0.24)
        self.layer.shadowRadius = size * 0.35
        self.layer.shadowOpacity = 0.8
    }
    
    func my_glowOnTap() {
        UIView.animate(withDuration: 0.25, delay: 0, animations: {
            self.alpha = 0.4
        }) { (_) in
            UIView.animate(withDuration: 0.4, animations: {
                self.alpha = 1
            })
        }
        
        
      
    }
}
<file_sep>//
//  RSSParser.swift
//  PHS App
//
//  Created by <NAME> on 8/29/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit

class NewsArticle: NSObject {
    
    var title = String()
    var link = String()
    var pubDate = Date()
    var author = String()
    var category1 = String()
    var category2: String?
    var category3: String?
    var content = String()
    var image: UIImage?
    var imageLink: URL?
    
}
<file_sep>//
//  MyClasses+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension MyClasses {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<MyClasses> {
        return NSFetchRequest<MyClasses>(entityName: "MyClasses")
    }

    @NSManaged public var period1: String?
    @NSManaged public var period2: String?
    @NSManaged public var period3: String?
    @NSManaged public var period4: String?
    @NSManaged public var period5: String?
    @NSManaged public var period6: String?
    @NSManaged public var period7: String?
    @NSManaged public var period8: String?

}
<file_sep>//
//  JoinViewController.swift
//  PHS App
//
//  Created by <NAME> on 10/2/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class JoinViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var invitedLabel: UILabel!
    @IBOutlet weak var information: UILabel!
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    @IBOutlet weak var joinButton: UIView!
    let joinLabel = UILabel()
    
    @IBAction func backTapped(_ sender: Any) {
        dismiss(animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        UIView.animate(withDuration: 0.3) {
            self.joinButton.backgroundColor = UIColor.clear
        }
       
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        joinButton.layer.cornerRadius = joinButton.bounds.height / 2
        joinButton.layer.borderWidth = 1.5
        joinButton.layer.borderColor = UIColor.black.cgColor
        joinLabel.bounds = joinButton.bounds
        joinLabel.center = CGPoint(x: joinButton.bounds.width / 2, y: joinButton.bounds.height / 2)
        joinLabel.textAlignment = .center
        joinLabel.textColor = UIColor.black
        joinLabel.text = "TALK TO US!"
        joinLabel.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth)
        joinButton.addSubview(joinLabel)
        let joinGesture = UITapGestureRecognizer(target: self, action: #selector(joinTapped))
        joinGesture.delegate = self
        joinButton.addGestureRecognizer(joinGesture)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        invitedLabel.font = invitedLabel.font.withSize(invitedLabel.font.pointSize.relativeToWidth)
        
        information.font = information.font.withSize(information.font.pointSize.relativeToWidth.relativeToWidth)
        topConstraint.constant = topConstraint.constant.relativeToWidth
    }
    

    @objc func joinTapped() {
       
        UIView.animate(withDuration: 0.3, animations: {
              self.joinButton.backgroundColor = UIColor.lightGray
        }) { (_) in
             self.joinButton.backgroundColor = UIColor.clear
        }
        guard let url = URL(string: "https://forms.gle/TSarYRRYZ6pDjXVK6") else { return }
        UIApplication.shared.open(url)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  MyClasses+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(MyClasses)
public class MyClasses: NSManagedObject {

}
<file_sep># Uncomment the next line to define a global platform for your project

platform :ios, '10.0'

target 'PHS App' do

  use_frameworks!

  # Pods for PHS App
pod 'RSBarcodes_Swift' , '~> 4.2.0'
pod 'Segmentio', '~> 3.0'
pod 'ExpandableCell'
pod 'TextFieldEffects'
pod 'JTAppleCalendar', '~> 7.1'
pod 'XLActionController'
pod 'XLActionController/Skype'
pod "SwiftyXMLParser"
pod "SDWebImage", '~> 4.0'
pod "PickerView"

pod 'OneSignal', '>= 2.6.2', '< 3.0'





pod 'Firebase/Core'
pod 'Fabric', '~> 1.7.11'
pod 'Crashlytics', '~> 3.10.7'
pod 'Firebase/Messaging'


  target 'PHS AppTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'PHS AppUITests' do
    inherit! :search_paths
    # Pods for testing

  end

 

  
end

   target 'OneSignalNotificationServiceExtension' do
	use_frameworks!
     pod 'OneSignal', '>= 2.6.2', '< 3.0'
  end


post_install do |installer|
    installer.pods_project.build_configurations.each do |config|
        config.build_settings.delete('CODE_SIGNING_ALLOWED')
        config.build_settings.delete('CODE_SIGNING_REQUIRED')
    end
end
<file_sep>//
//  HouseRankCollectionViewCell.swift
//  PHS App
//
//  Created by <NAME> on 10/3/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class HouseRankCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var house: UILabel!
    @IBOutlet weak var points: UILabel!
    
}
<file_sep>//
//  TeachersViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/13/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import Segmentio
import CoreData
import CoreGraphics
import ExpandableCell

 var fetchedTeachersCount = 0
var fetchedCoachesCount = 0


 func fetchTeachers() {
    print("CALLED FETCHED TEACEHRS")
    if let data = Bundle.main.path(forResource: "teachersInfo", ofType: "txt") {
        if let content = try? String(contentsOfFile: data) {
            if let jsonData = JSON(parseJSON: content).dictionaryValue["teachers"]?.arrayValue {
          
                for member in jsonData {
                    let detail = member.dictionaryObject!
                    let object = NewTeachers()
                    if let first = detail["first"] as? String {
                        object.first = first
                    }
                    if let last = detail["last"] as? String {
                        object.last = last
                    }
                    if let subject1 = detail["subject1"] as? String {
                        object.subject1 = subject1
                    }
                    if let subject2 = detail["subject2"] as? String {
                        object.subject2 = subject2
                    } else {
                        object.subject2 = nil
                    }
                    if let isFemale = detail["isFemale"] as? Bool {
                        object.isFemale = isFemale
                    }
                    localTeachers.append(object)
                }
           
            }
        }
    }
    
    localTeachers = uniq(source: localTeachers)
    
    
    }


        
func generateAlphaDict() {
    for teacher in localTeachers {
        let key = "\(teacher.last[(teacher.last.startIndex)])"
        let upper = key.uppercased()
        if var teacherInfo = teachersAlphaDict[upper] {
            teacherInfo.append(teacher)
            teachersAlphaDict[upper] = teacherInfo
        } else {
            teachersAlphaDict[upper] = [teacher]
        }
    }
    teachersAlphaSections = [String](teachersAlphaDict.keys)
    teachersAlphaSections = teachersAlphaSections.sorted()
}

func generateSubjectsDict() {
    for teacher in localTeachers {
        if teacher.subject2 != nil {
           
            var key = teacher.subject1
            var key2 = teacher.subject2!
            if key == "Spanish" || key == "French" || key == "Chinese" {
                key = "World Language"
            }   else if key == "Principal" || key == "Assistant Principal" || key == "Administrative Assistant" || key == "Lead Counselor" || key == "Athletic Director" {
                adminDictionary[teacher] = key
                adminRows.append(teacher)
                key = "Administration"
            }
            if  key2 == "Spanish" || key2 == "French" || key2 == "Chinese" {
                key2 = "World Language"
            } else if key2 == "Principal" || key2 == "Assistant Principal" || key2 == "Administrative Assistnat" || key2 == "Lead Counselor" || key2 == "Athletic Director" {
                adminDictionary[teacher] = key
                adminRows.append(teacher)
                key2 = "Administration"
            }
            let upper = key.uppercased()
            let upper2 = key2.uppercased()
            if var teacherSubject = subjectsDictionary[upper] {
                teacherSubject.append(teacher)
                subjectsDictionary[upper] = teacherSubject
            } else {
                subjectsDictionary[upper] = [teacher]
            }
            if var teacherSubject2 = subjectsDictionary[upper2] {
                teacherSubject2.append(teacher)
                subjectsDictionary[upper2] = teacherSubject2
            } else {
                subjectsDictionary[upper2] = [teacher]
            }
            
        } else {
            var key = teacher.subject1
            if key == "Spanish" || key == "French" || key == "Chinese" {
                key = "World Language"
            }   else if key == "Principal" || key == "Assistant Principal" || key == "Administrative Assistant" || key == "Lead Counselor" || key == "Athletic Director" {
                adminDictionary[teacher] = key
                adminRows.append(teacher)
                key = "Administration"
            }
            let upper = key.uppercased()
            if var teacherSubject = subjectsDictionary[upper] {
                teacherSubject.append(teacher)
                subjectsDictionary[upper] = teacherSubject
            } else {
                subjectsDictionary[upper] = [teacher]
            }
 
    }
    
    subjectsDictionary = subjectsDictionary.filter {$0.key != "ADMINISTRATION"}
    subjectsRows = subjectsRows.filter { $0 != "ADMINISTRATION" }
    subjectsRows = [String](subjectsDictionary.keys)
    subjectsRows = subjectsRows.sorted()
}
}

var savedTeachers = [Teachers]()
var localTeachers = [NewTeachers]()
var teachersAlphaDict = [String: [NewTeachers]]()
var teachersAlphaSections = [String]()
var subjectsDictionary = [String: [NewTeachers]]()
var subjectsRows = [String]()
var adminDictionary = [NewTeachers: String]()
var adminRows = [NewTeachers]()
var savedCoaches = [Coaches]()
var coachesTeamDictionary = [String: [Coaches]]()
var coachesRows = [String]()

 var myClasses = [String?]()
  var masterSchedule = [MySchedule]()

class TeachersViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {


    var underConstructionView = UnderConstructionView()
    @IBOutlet var navigationBar: UINavigationBar!
    @IBAction func dismiss(_ sender: Any) {
        dismiss(animated: true)
    }
    
    
    @IBOutlet var editButton: UIBarButtonItem!
    @IBAction func editTapped(_ sender: Any) {
        performSegue(withIdentifier: "editClasses", sender: nil)
    }
    
    
    @IBOutlet weak var segmentioView: Segmentio!
    var content = [SegmentioItem]()
    
    @IBOutlet weak var allTableView:  UITableView!
    @IBOutlet weak var subjectsTableView: ExpandableTableView!
   
    @IBOutlet weak var adminTableView: UITableView!
    var coachesTableView = ExpandableTableView()
    
    @IBOutlet weak var noTeachersView: UIView!
    var fillTeachersButton = UIView()
    var fillInLabel = UILabel()
    
    var myTeachers = [MyNewTeachers]()
 
    var classesToDisplay = [String?]()
    var displaySchedule = [MySchedule]()
    var allTeachersCount = Int()
    var allCoachesCount = Int()
   var displayCoaches = Bool()
    
    @IBOutlet weak var myTeachersTableView: UITableView!
    
    
    func reload() {
        self.coachesTableView.reloadData()
        self.allTableView.reloadData()
        self.subjectsTableView.reloadData()
        self.adminTableView.reloadData()
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
        setSegmentedControl()
        if localTeachers.count == 0 {
            fetchTeachers()
        }
        configrueTableViews()
        if teachersAlphaDict.count == 0 {
            generateAlphaDict()

        }
        if subjectsDictionary.count == 0 {
            generateSubjectsDict()

        }
        
        self.view.bringSubviewToFront(self.allTableView)
        
        let scheduleFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest()
        do {
          let request = try PersistentService.context.fetch(scheduleFetchRequest)
            if request.count > 0 {
                var scheduleArray = request
                scheduleArray.sort { $0.period < $1.period }
                masterSchedule = scheduleArray
                for entry in scheduleArray {
                    myClasses.append(entry.name)
                }
             
                classesToDisplay = myClasses.filter { $0 != "Free Period" && $0 != "Sports" && $0 != "Sport" }
                displaySchedule = masterSchedule.filter {$0.name != "Free Period" && $0.name != "Sports" && $0.name != "Sport" }
               
            } else {
                myClasses = []
                classesToDisplay = []
            }
            
           
        } catch {
            
        }
        
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(fillInTapped))
       gestureRecognizer.delegate = self
        fillTeachersButton.addGestureRecognizer(gestureRecognizer)
        
      
        segmentioView.selectedSegmentioIndex = 0
        
       
        
    }
    
    @objc func fillInTapped() {
                performSegue(withIdentifier: "fillClasses", sender: nil)

    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
      
      
        segmentioView.valueDidChange = { segmentio, segmentIndex in
            switch segmentIndex {
          
          
            case 0:
                self.view.bringSubviewToFront(self.allTableView)
            case 1:
                self.view.bringSubviewToFront(self.subjectsTableView)
            case 2:
                self.view.bringSubviewToFront(self.adminTableView)
            case 3:
                if self.displayCoaches {
                    self.view.bringSubviewToFront(self.coachesTableView)
                } else {
                    self.view.bringSubviewToFront(self.underConstructionView)
                }
            default:
                print("more coming")
            }
        }

    }
    

    func setSegmentedControl() {
        
        let position = SegmentioPosition.dynamic
        let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white)
        let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none)
        let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0))
        segmentioView.selectedSegmentioIndex = 0
        let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: (
            defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)),
            selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white),
            highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white)
            )
            ,animationDuration: 0.2)
        let allItem = SegmentioItem(title: "ALL", image: nil)
        let subjectsItem = SegmentioItem(title: "SUBJECTS", image: nil)
        let adminItem = SegmentioItem(title: "ADMIN", image: nil)
        content = [allItem, subjectsItem, adminItem]
        segmentioView.setup(content: content, style: .onlyLabel, options: options)
        
    }
    
    func configrueTableViews() {
       
        allTableView.delegate = self
        allTableView.dataSource = self
        subjectsTableView.expandableDelegate = self
        subjectsTableView.register(UINib(nibName: "SubjectsExpandableTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandableTableViewCell.ID)
        subjectsTableView.register(UINib(nibName: "SubjectsExpandedTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandedTableViewCell.ID)
        
        adminTableView.delegate = self
        adminTableView.dataSource = self
        
        
        coachesTableView.expandableDelegate = self
        coachesTableView.animation = .automatic
        coachesTableView.register(UINib(nibName: "SubjectsExpandableTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandableTableViewCell.ID)
        coachesTableView.register(UINib(nibName: "SubjectsExpandedTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandedTableViewCell.ID)
        
        
   
        fillTeachersButton.frame = CGRect(x: 0, y: 0, width: CGFloat(250).relativeToWidth, height: CGFloat(50).relativeToWidth)
        fillTeachersButton.center = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.height / 2 - CGFloat(100).relativeToWidth)
        fillTeachersButton.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
        fillTeachersButton.layer.cornerRadius = CGFloat(25).relativeToWidth
        fillInLabel.bounds = CGRect(x: 0, y: 0, width: fillTeachersButton.bounds.width, height: fillTeachersButton.bounds.height)
        fillInLabel.center = CGPoint(x: fillTeachersButton.bounds.width / 2, y: fillTeachersButton.bounds.height / 2)
        fillInLabel.text = "FILL IN YOUR SCHEDULE"
        fillInLabel.textAlignment = .center
        fillInLabel.font = UIFont(name: "Lato-Bold", size: CGFloat(17).relativeToWidth)
        fillInLabel.textColor = UIColor.white
        fillTeachersButton.addSubview(fillInLabel)
        fillTeachersButton.my_dropShadow()
       
        
        myTeachersTableView.delegate = self
        myTeachersTableView.dataSource = self
        
        
    }
    
   
    

    

    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView == allTableView {
           
             return teachersAlphaSections.count
        } else if tableView == adminTableView {
            return 1
        } else if tableView == myTeachersTableView {
            return 1
        }
       return 0
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        
        if tableView == allTableView {
            
            return teachersAlphaSections[section]
        }
        return nil
    }


    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView == allTableView {
            return CGFloat(40).relativeToWidth
        }
        return 0
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if tableView == allTableView {
            let headerView = UIView()
            headerView.backgroundColor = UIColor(red:0.99, green:0.95, blue:1.00, alpha:1.0)
            let headerLabel = UILabel(frame: CGRect(x: CGFloat(30).relativeToWidth, y: CGFloat(5).relativeToWidth, width: allTableView.bounds.size.width, height: self.tableView(tableView, heightForHeaderInSection: section)))
            
            headerLabel.font = UIFont(name: "Lato-Bold", size: CGFloat(22).relativeToWidth)
            headerLabel.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
            headerLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
            headerLabel.sizeToFit()
            headerView.addSubview(headerLabel)
            return headerView
        }
        return nil
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == allTableView {
            let teacherKey = teachersAlphaSections[section]
            if let teacherValues = teachersAlphaDict[teacherKey] {
                return teacherValues.count
            }
        } else if tableView == adminTableView {
            return adminRows.count
        } else if tableView == myTeachersTableView {
            return displaySchedule.count
        }
      
        return 0
    }



    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = Bundle.main.loadNibNamed("AllTableViewControllerCellTableViewCell", owner: self, options: nil)?.first as! AllTableViewControllerCellTableViewCell
       
        if tableView == allTableView {
           
            let teacherKey = teachersAlphaSections[indexPath.section]
            
            if let teacherValues = teachersAlphaDict[teacherKey.uppercased()] {
                let teacher = teacherValues[indexPath.row]
                cell.first = teacher.first
                cell.last = teacher.last
                cell.gender = teacher.isFemale
                cell.name.text = "\(teacher.first.uppercased()) \(teacher.last.uppercased())"
                cell.name.font = cell.name.font.withSize(CGFloat(16).relativeToWidth)
                if teacher.subject2 != nil {
                    cell.subject.text = "\(teacher.subject1.uppercased()) & \(teacher.subject2!.uppercased())"
                } else {
                    cell.subject.text = "\(teacher.subject1.uppercased())"
                }
                cell.subject.font = cell.subject.font.withSize(CGFloat(16).relativeToWidth.relativeToWidth)
                cell.initialsLabel.text = "\(Array(teacher.first)[0])\(Array(teacher.last)[0])"
                cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(19).relativeToWidth)
                
                return cell
            }
        } else if tableView == adminTableView {
            let admin = adminRows[indexPath.row]
            var role = String()
            if admin.subject1 == "Principal" || admin.subject1 == "Assistant Principal" || admin.subject1 == "Lead Counselor" || admin.subject1 == "Athletic Director" || admin.subject1 == "Administrative Assistant" {
                role = admin.subject1.uppercased()
            } else {
                role = (admin.subject2?.uppercased())!
            }
           
            cell.first = admin.first
            cell.last = admin.last
            cell.gender = admin.isFemale
            cell.name.text = "\(admin.first.uppercased()) \(admin.last.uppercased())"
            cell.name.font = cell.name.font.withSize(CGFloat(16).relativeToWidth)
            cell.initialsLabel.text = "\(Array(admin.first)[0])\(Array(admin.last)[0])"
            cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(19).relativeToWidth)
            cell.subject.text = role
            return cell
        } else if tableView == myTeachersTableView {
            let myCell = Bundle.main.loadNibNamed("MyTeachersTableViewCell", owner: self, options: nil)?.first as! MyTeachersTableViewCell
            if displaySchedule.count != 0 {
                let schedule = displaySchedule[indexPath.row]
                
                myCell.first = schedule.teacher!.first!
                myCell.last = schedule.teacher!.last!
                myCell.gender = schedule.teacher!.isFemale
                myCell.initialsLabel.text = "\(Array(myCell.first)[0])\(Array(myCell.last)[0])"
                myCell.teacherLabel.text = "\(myCell.first.uppercased()) \(myCell.last.uppercased())"
                myCell.periodLabel.text = "PERIOD \(schedule.period)"
                myCell.classLabel.text = schedule.name!
            }
            
            
            
            return myCell
            
            }
            
            
        
      

        return UITableViewCell()
}

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if tableView == myTeachersTableView {
            return CGFloat(80)
        }
        return CGFloat(70).relativeToWidth
    }

    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if tableView == allTableView {
            allTableView.sectionIndexColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
            return teachersAlphaSections
        }
        return nil
    }
    

    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "fillClasses" {
            if let vc = segue.destination as? PickClassesViewController {
                vc.isFreshLaunch = false
                vc.isPrevButtonHidden = true
                
            }
        } else if segue.identifier == "editClasses" {
            if let vc = segue.destination as? PickClassesViewController {
                vc.isPageEditing = true
                vc.isFreshLaunch = false
                vc.isPrevButtonHidden = true
                vc.mySelectedTeachers = self.myTeachers
                vc.periods = myClasses
                
                
            }
        }
    }
    
    @IBAction func skipFromSecondScreen(segue: UIStoryboardSegue) {
        if segue.identifier == "skipFromSecondScreen" {
            print("skipped from second page")
        
        }
    }
    
    @IBAction func newInfoSaved(segue: UIStoryboardSegue) {
        if segue.identifier == "newInfoSaved" {
            if let vc = segue.source as? PickTeachersViewController {
           
                for i in 0...7 {
                    let newSchedule = MySchedule(context: PersistentService.context)
                    newSchedule.name = vc.classes[i]
                    newSchedule.period = Int16(i + 1)
                    let newTeacher = MyNewTeachers(context: PersistentService.context)
                    let currentTeacher = vc.myTeachers[i]
                    newTeacher.first = currentTeacher?.first
                    newTeacher.last = currentTeacher?.last
                    newTeacher.subject1 = currentTeacher?.subject1
                    newTeacher.subject2 = currentTeacher?.subject2
                    newTeacher.isFemale = currentTeacher?.isFemale ?? false
                    newSchedule.teacher = newTeacher
                    PersistentService.saveContext()
                }
            }
            fetchAndReload(withClasses: true)
            navigationBar.topItem?.rightBarButtonItem = editButton
        }
    }
    
    
    @IBAction func unwindToTeacherPage(segue: UIStoryboardSegue) {
        if segue.identifier == "unwindToTeacherPage" {
            if let vc = segue.source as? PickTeachersViewController {
                let scheduleFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest()
                let teacherFetchRequest: NSFetchRequest<MyNewTeachers> = MyNewTeachers.fetchRequest()
                do {
                    let request = try PersistentService.context.fetch(scheduleFetchRequest)
                    let teacherRequest = try PersistentService.context.fetch(teacherFetchRequest)
                    var requestSort = request
                    requestSort.sort {$0.period < $1.period}
                    for i in 0...requestSort.count - 1 {
                        print(requestSort[i].name)
                    }
                    for i in 0...teacherRequest.count - 1 {
                        print(teacherRequest[i].first)
                    }
                    
                    var tracker = 0
                    
                    for i in 0...7 {
                        
                        let object = requestSort[i]
                        object.setValue(vc.classes[i], forKey: "name")
                        object.setValue(Int16(i + 1), forKey: "period")
                        if vc.classes[i] == "Sports" || vc.classes[i] == "Free Period" {
                            object.setValue(nil, forKey: "teacher")
                        } else {
                            if tracker > teacherRequest.count - 1 {
                                let newTeacher = MyNewTeachers(context: PersistentService.context)
                                let currentTeacher = vc.myTeachers[i]
                                newTeacher.first = currentTeacher?.first
                                newTeacher.last = currentTeacher?.last
                                newTeacher.subject1 = currentTeacher?.subject1
                                newTeacher.subject2 = currentTeacher?.subject2
                                newTeacher.isFemale = currentTeacher?.isFemale ?? false
                                 object.setValue(newTeacher, forKey: "teacher")
                            } else {
                                let newTeacher = teacherRequest[tracker]
                                let currentTeacher = vc.myTeachers[i]
                                newTeacher.setValue(currentTeacher?.first, forKey: "first")
                                newTeacher.setValue(currentTeacher?.last, forKey: "last")
                                newTeacher.setValue(currentTeacher?.subject1, forKey: "subject1")
                                newTeacher.setValue(currentTeacher?.subject2, forKey: "subject2")
                                newTeacher.setValue(currentTeacher?.isFemale, forKey: "isFemale")
                                object.setValue(newTeacher, forKey: "teacher")
                            }
                        
                            tracker += 1
                            
                        }
                        
                        PersistentService.saveContext()
                    }
                } catch {
                    
                }

            
                
               
            }
            
            fetchAndReload(withClasses: true)
            navigationBar.topItem?.rightBarButtonItem = editButton
            
        }
        
    }
    
    
    func fetchAndReload(withClasses: Bool) {
        
        let scheduleFetch: NSFetchRequest<MySchedule> = MySchedule.fetchRequest()
        do {
            let request = try PersistentService.context.fetch(scheduleFetch)
            masterSchedule = request
            masterSchedule.sort { $0.period < $1.period }
         
        } catch {
            
        }
        
        displaySchedule = masterSchedule.filter {$0.name != "Free Period" && $0.name != "Sports" && $0.name != "Sport" }
        
        view.bringSubviewToFront(myTeachersTableView)
       
        for item in displaySchedule {
            myTeachers.append(item.teacher!)
        }
        
        myTeachersTableView.reloadData()
       
    }
 
}




extension TeachersViewController: ExpandableDelegate {
     func numberOfSections(in expandableTableView: ExpandableTableView) -> Int {
        return 1
    }
    
    func expandableTableView(_ expandableTableView: ExpandableTableView, numberOfRowsInSection section: Int) -> Int {
        if expandableTableView == subjectsTableView {
            return subjectsRows.count

        } else if expandableTableView == coachesTableView {
            return coachesRows.count
        }
        return 1
    }
    
    
    func expandableTableView(_ expandableTableView: ExpandableTableView, expandedCellsForRowAt indexPath: IndexPath) -> [UITableViewCell]? {
        if expandableTableView == subjectsTableView {
            let department = subjectsRows[indexPath.row]
            var expandedArray = [SubjectsExpandedTableViewCell]()
            if let teachers = subjectsDictionary[department] {
                
                for teacher in teachers {
                    let cell = subjectsTableView.dequeueReusableCell(withIdentifier: SubjectsExpandedTableViewCell.ID) as! SubjectsExpandedTableViewCell
                    
                    cell.first = teacher.first
                    cell.last = teacher.last
                    cell.gender = teacher.isFemale
                    cell.email = nil
                    cell.nameLabel.text = "\(teacher.first.uppercased()) \(teacher.last.uppercased())"
                    cell.nameLabel.font = cell.nameLabel.font.withSize(CGFloat(16).relativeToWidth)
                    cell.initialsLabel.text = "\(Array(teacher.first)[0])\(Array(teacher.last)[0])"
                    cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(16).relativeToWidth)
                    expandedArray.append(cell)
                }
                return expandedArray
            } else {
                return nil
            }
        } else if expandableTableView == coachesTableView {
            let team = coachesRows[indexPath.row]
            var expandedArray = [SubjectsExpandedTableViewCell]()
            if let coaches = coachesTeamDictionary[team] {
                for coach in coaches {
                    let cell = subjectsTableView.dequeueReusableCell(withIdentifier: SubjectsExpandedTableViewCell.ID) as! SubjectsExpandedTableViewCell
                    cell.first = coach.first ?? " "
                    cell.last = coach.last ?? " "
                    cell.email = coach.email
                    cell.gender = coach.gender
                    cell.nameLabel.text = "\(coach.first?.uppercased() ?? "") \(coach.last?.uppercased() ?? "")"
                    cell.nameLabel.font = cell.nameLabel.font.withSize(CGFloat(16).relativeToWidth)
                    cell.initialsLabel.text = "\(Array(coach.first!)[0])\(Array(coach.last!)[0])"
                    cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(16).relativeToWidth)
                    expandedArray.append(cell)
                    
                }
                return expandedArray
            } else {
                return nil
            }
            
        }
      
        return nil
    }
    
    func expandableTableView(_ expandableTableView: ExpandableTableView, heightsForExpandedRowAt indexPath: IndexPath) -> [CGFloat]? {
         var heightArray = [CGFloat]()
        if expandableTableView == subjectsTableView {
            if let teachers = self.expandableTableView(expandableTableView, expandedCellsForRowAt: indexPath){
                for _ in teachers {
                    heightArray.append(CGFloat(65).relativeToWidth)
                }
                return heightArray
            } else {
                return nil
            }
        } else if expandableTableView == coachesTableView {
            if let coaches = self.expandableTableView(expandableTableView, expandedCellsForRowAt: indexPath) {
                for _ in coaches {
                    heightArray.append(CGFloat(65).relativeToWidth)
                }
                return heightArray
            } else {
                return nil
            }
        }
        
        
        return nil
    }
    

    
    func expandableTableView(_ expandableTableView: ExpandableTableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return CGFloat(50).relativeToWidth
        
    }
    
    
    
    func expandableTableView(_ expandableTableView: ExpandableTableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = subjectsTableView.dequeueReusableCell(withIdentifier: SubjectsExpandableTableViewCell.ID) as! SubjectsExpandableTableViewCell

        if expandableTableView == subjectsTableView {
            cell.subjectLabel.text = subjectsRows[indexPath.row]
            cell.subjectLabel.font = cell.subjectLabel.font.withSize(CGFloat(20).relativeToWidth)
            return cell
        } else if expandableTableView == coachesTableView {
            cell.subjectLabel.text = coachesRows[indexPath.row]
            cell.subjectLabel.font = cell.subjectLabel.font.withSize(CGFloat(20).relativeToWidth)
            return cell

        }

        return cell
    }
    
    func expandableTableView(_ expandableTableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        return true
    }

}
<file_sep>//
//  GameScheduleTableViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/20/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import EventKit
import EventKitUI
import UserNotifications

class GameScheduleTableViewCell: UITableViewCell {

    @IBOutlet weak var gameResultView: UIView!
    @IBOutlet weak var homeScore: UILabel!
    @IBOutlet weak var awayScore: UILabel!
    @IBOutlet weak var awayTeam: UILabel!
    @IBOutlet weak var homeTeam: UILabel!
    @IBOutlet weak var gameScheduleView: UIView!
    @IBOutlet weak var awayTeamSchedule: UILabel!
    @IBOutlet weak var bell: UIImageView!
    @IBOutlet weak var bellOutline: UIImageView!
    @IBOutlet weak var calendar: UIImageView!
    @IBOutlet weak var date: UILabel!
    @IBOutlet weak var weekday: UILabel!
    @IBOutlet weak var time: UILabel!
    @IBOutlet weak var isAway: UILabel!
  
    var notification = false
    var sport = String()
    var gameTime = Date()
    var otherTeam = String()
   let store = EKEventStore()
    var identifier = String()
  
    
    override func awakeFromNib() {
        super.awakeFromNib()
        bell.alpha = 0
      
        let labels: [UILabel] = [homeScore, awayScore, awayTeam, homeTeam, awayTeamSchedule, date, weekday, time, isAway]
        for label in labels {
            label.font = label.font.withSize(label.font.pointSize.relativeToWidth)
        }
        
        bellOutline.isUserInteractionEnabled = true
        calendar.isUserInteractionEnabled = true
        let bellGesture = UITapGestureRecognizer(target: self, action: #selector(bellTapped))
        bellGesture.delegate = self
        bellOutline.addGestureRecognizer(bellGesture)
        
        let calendarGesture = UITapGestureRecognizer(target: self, action: #selector(calendarTapped))
        calendarGesture.delegate = self
        calendar.addGestureRecognizer(calendarGesture)
    }
    
    @objc func bellTapped() {

            notification = !notification
           
        
                     if self.notification {
                        UIView.animate(withDuration: 0.3) {
                               self.bell.alpha = 1
                        }
                        self.scheduleLocal()

                     } else {
                        UIView.animate(withDuration: 0.3) {
                             self.bell.alpha = 0
                        }
                       
                        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
            
        }
        
    }

    @objc func calendarTapped() {

        let endTime = Calendar.current.date(byAdding: .hour, value: 1, to: gameTime)!
        createEventinTheCalendar(with: "\(sport) vs \(otherTeam)", forDate: gameTime, toDate: endTime)
    }
    
    func createEventinTheCalendar(with title: String, forDate eventStartDate: Date, toDate eventEndDate: Date) {
        
        store.requestAccess(to: .event) { (success, error) in
            if  error == nil {
                let event = EKEvent.init(eventStore: self.store)
                event.title = title
                event.calendar = self.store.defaultCalendarForNewEvents
                event.startDate = eventStartDate
                event.endDate = eventEndDate
                
                let alarm = EKAlarm.init(absoluteDate: Date.init(timeInterval: -3600, since: event.startDate))
                event.addAlarm(alarm)
                
                do {
                    try self.store.save(event, span: .thisEvent)
                    let ac = UIAlertController(title: "Saved Successfully", message: "We have saved this game to your calendar.", preferredStyle: .alert)
                    ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    self.parentViewController?.present(ac, animated: true)
                } catch {
                
                    let ac = UIAlertController (title: "Could not save evnent", message: "There was an error saving your event, go to settings to double-check calendar usage permission.?", preferredStyle: .alert)
                    
                    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
                        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                            return
                        }
                        
                        if UIApplication.shared.canOpenURL(settingsUrl) {
                            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                                
                            })
                        }
                    }
                    ac.addAction(settingsAction)
                    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
                    ac.addAction(cancelAction)
                    
                   self.parentViewController?.present(ac, animated: true, completion: nil)
                    
                }
                
            } else {
                //we have error in getting access to device calnedar
                 self.setAlertController(title: "Could not save evnent", message: "There was an error saving your event, go to settings to double-check calendar usage permission.", preferredStyle: .alert, actionTitle: "OK")
            }
        }
    }
    
    func scheduleLocal() {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print(self.gameTime)
                let dateComponents = Calendar.current.dateComponents([.minute, .hour, .day, .month, .year], from: self.gameTime)
                let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
//                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
                let content = UNMutableNotificationContent()
                content.title = "\(self.sport) vs \(self.otherTeam)"
                content.body = "\(self.sport)'s will play \(self.otherTeam) soon, go to the game and show your support!"
                content.sound = UNNotificationSound.default
            
               
                let request = UNNotificationRequest(identifier: self.identifier, content: content, trigger: trigger)
                center.add(request)
            } else {
                let ac = UIAlertController (title: "No Permission", message: "We do not have permission to send you notifications, would you like to change that in settings?", preferredStyle: .alert)
                
                let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
                    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                        return
                    }
                    
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                            
                        })
                    }
                }
                ac.addAction(settingsAction)
                let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
                ac.addAction(cancelAction)
                
                self.parentViewController?.present(ac, animated: true, completion: nil)
                }
        }
    }
    
    
    
    func setAlertController(title: String, message: String?, preferredStyle: UIAlertController.Style, actionTitle: String) {
        let ac = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
        ac.addAction(UIAlertAction(title: actionTitle, style: .default, handler: nil))
        self.parentViewController?.present(ac, animated: true)
    }
    
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}
<file_sep>//
//  DayType+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 8/10/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(DayType)
public class DayType: NSManagedObject {

}
<file_sep>//
//  UpcomingGamesCollectionViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/20/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class UpcomingGamesCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var team: UILabel!
    @IBOutlet weak var location: UILabel!
    @IBOutlet weak var date: UILabel!
    @IBOutlet weak var purpleCircle: UIView!
    @IBOutlet weak var P: UILabel!
    @IBOutlet weak var grayCircle: UIView!
    @IBOutlet weak var awayInitial: UILabel!
    @IBOutlet weak var PortolaLabel: UILabel!
    @IBOutlet weak var awayLabel: UILabel!
    
}
<file_sep>//
//  FirstScanViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/19/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import RSBarcodes_Swift
import AVFoundation

class FirstScanViewController: RSCodeReaderViewController {

    @IBOutlet weak var frameView: UIView!
    @IBAction func buttonTapped(_ sender: Any) {
        longID = nil
      performSegue(withIdentifier: "backToID", sender: nil)
    }
    
    var longID: String?
    var shouldReturn = true
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) ==  AVAuthorizationStatus.authorized {
            //continue
        } else {
            AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in
                if granted == true {
                
                } else {
                    let ac = UIAlertController (title: "No Camera Usage Permission", message: "You have denied the app's camera usage, please go to settings to double-check camera usage permission.?", preferredStyle: .alert)
                    
                    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
                        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                            return
                        }
                        
                        if UIApplication.shared.canOpenURL(settingsUrl) {
                            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                                
                            })
                        }
                    }
                    ac.addAction(settingsAction)
                    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_) in
                        self.dismiss(animated: true)
                    })
                    ac.addAction(cancelAction)
                    
                   self.present(ac, animated: true, completion: nil)
                }
                
            })
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        frameView.backgroundColor = UIColor.white.withAlphaComponent(0)
        frameView.layer.borderColor = UIColor.white.cgColor
        frameView.layer.borderWidth = 2
        
      
      
        
        
        self.focusMarkLayer.strokeColor = UIColor.yellow.cgColor
        
        self.cornersLayer.strokeColor = UIColor.yellow.cgColor
        
      
        
        
        self.barcodesHandler = { barcodes in
            let barcode = barcodes.first!
           
            if self.shouldReturn {
                self.longID = barcode.stringValue!
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                    self.performSegue(withIdentifier: "backToID", sender: nil)
                })
            }
            self.shouldReturn = false

        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  HouseCollectionViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class HouseCollectionViewCell: UICollectionViewCell {
    var label = UILabel()
    var roundedRect = UIView()
}
<file_sep>//
//  my_notificationPrompt.swift
//  PHS App
//
//  Created by <NAME> on 8/29/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func my_notificationPrompt(type: Int) -> String {
    
    switch type {
    case 0:
        return "nothing"
    case 1:
        //pep assembly odd
        return "There is a pep assembly tomorrow. School starts at 8:00 and ends at 3:30."
    case 2:
        //pep assembly even
        return "There is a pep assembly tomorrow. School starts at 8:00 and ends at 3:30."
    case 3:
        //extended lunch odd
        return "There is an extended lunch tomorrow, lunch will be 49 minutes long from 11:33 to 12:22."
    case 4:
        //extended lunch even
        return "There is an extended lunch tomorrow, lunch will be 49 minutes long from 11:33 to 12:22."
        
    case 5:
        //finals type 1
        return "Tomorrow is Finals, you will have 1st, 3rd and 7th period. School will start at 8:00 and end at 12:29."
    case 6:
        //finals type 2
        return "Tomorrow is Finals, you will have 2st, 4th and 8th period. School will start at 8:00 and end at 12:29."
    case 7:
        //finals two periods
        return "Tomorrow is Finals, you will have 5th and 6th period. School will start at 8:00 and end at 11:00."
    case 8:
        //minimum 1-8
        return "Tomorrow is minimum day, you will have period 1-8. School will start at 8:00 and end at 12:28."
    case 9:
        //conferences odd
        return "Tomorrow is minimum day, you will have odd periods. School will start at 8:00 and end at 12:28."
    case 10:
        //conferences even
        return "Tomorrow is minimum day, you will have even periods. School will start at 8:00 and end at 12:28."
    case 11:
        //PSAT 9
        return "Tomorrow is freshmen PSAT. Freshmen will start testing at 8:00 and Sophomores & Juniors will start at 11:20. You will have odd periods."
    case 12:
        //PE testing
        return "Tomorrow is freshmen PE Testing. Freshmen will start testing at 8:30 and Sophomores & Juniors will start at 11:20. You will have odd periods."
        
    case 13:
        //first 2 days of school
        return "passed"
        
    case 14:
        // hour of code
        return "Tomorrow is hour of code. You will have advisement instead of office hours."
    case 15:
        //Passion Day
        return "Tomorrow is passion day. School will start at 8:00and end at 2:31."
    case 16:
        //Pre Testing
        return "Tomorrow is pre-testing schedule. School will start at 8:30, you will have period 1, 2, 3, 5 and 7."
    case 17:
        //Testing
        return "Tomorrow is sophomores and juniors testing. School will start at 8:00 for sophomores and juniors, and 11:30 for freshmen."
    case 18:
        //CAASPP odd
        return "Tomorrow is juniors CAASPP testing. School will start at 8:00 for juniors and 11:20 for freshmen and sophomores. You will have odd periods."
    case 19:
        //CAASPP even
        return "Tomorrow is juniors CAASPP testing. School will start at 8:00 for juniors and 11:20 for freshmen and sophomores. You will have even periods."
    case 20:
        //NO SCHOOL
        return "No school tomorrow! Enjoy your day off!"
    case 21:
        //fine arts assembly
        return "Tomorrow is fine arts assembly. School will start at 8:00 and end at 3:30."
    case 22:
        //monday schedule
        return "Tomorrow we will have Monday schedule."
    case 23:
        //tuesday schedule
        return "Tomorrow we will have Tuesday schedule."
    case 24:
        //wednesday schedule
        return "Tomorrow we will have Wednesday schedule."
    case 25:
        //thursday schedule
        return "Tomorrow we will have Thursday schedule."
    case 26:
        //friday schedule
        return "Tomorrow we will have Friday schedule."
    default:
        return "nothing"
    }
}



<file_sep>//
//  my_numOfMinDuringSchool.swift
//  PHS App
//
//  Created by <NAME> on 8/4/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func numOfMinAtSchool(type: Int) -> Int? {
    let schedule = my_getSchedule(type: type, date: nil) 
    if type == 20 {
        return nil
    } else {
        if Calendar.current.component(.weekday, from: Date()) == 1 || Calendar.current.component(.weekday, from: Date()) == 7 {
            return nil
        } else {
              let start = schedule!.first!
            let end = schedule!.last!
            if let interval = Calendar.current.dateComponents([.minute], from: start, to: end).minute {
                return interval
            } else {
                return nil
            }
            
            
        }
    }
   
}
<file_sep>//
//  my_getWeekdayString.swift
//  PHS App
//
//  Created by <NAME> on 7/29/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func getWeekdayString(date: Date, isUpper: Bool) -> String {
    let weekday = Calendar.current.component(.weekday, from: date)
    if isUpper {
        switch weekday {
        case 1:
            return "SUNDAY"
        case 2:
            return "MONDAY"
        case 3:
            return "TUESDAY"
        case 4:
            return "WEDNESDAY"
        case 5:
            return "THURSDAY"
        case 6:
            return "FRIDAY"
        case 7:
            return "SATURDAY"
        default:
            return "COMING UP"
        }
    } else {
        switch weekday {
        case 1:
            return "Sunday"
        case 2:
            return "Monday"
        case 3:
            return "Tuesday"
        case 4:
            return "Wednesday"
        case 5:
            return "Thursday"
        case 6:
            return "Friday"
        case 7:
            return "Satueday"
        default:
            return "Coming Up"
        }
    }
   
    
    
}
<file_sep>//
//  AthleticsCollectionViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/20/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class AthleticsCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var iconImage: UIImageView!
    @IBOutlet weak var iconLabel: UILabel!
}
<file_sep>//
//  AllTableViewControllerCellTableViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/16/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreGraphics
import MessageUI

class AllTableViewControllerCellTableViewCell: UITableViewCell, MFMailComposeViewControllerDelegate {
    @IBOutlet weak var initialsLabel: UILabel!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var subject: UILabel!
    @IBOutlet weak var email: UIImageView!
    @IBOutlet weak var circleImageView: UIImageView!
    var first = String()
    var last = String()
    var gender = Bool()
    
    override func awakeFromNib() {
        super.awakeFromNib()
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(emailTapped))
        gestureRecognizer.delegate = self
        email.addGestureRecognizer(gestureRecognizer)
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: self.frame.height * 0.9, height: self.frame.height * 0.9))
        let img = renderer.image { ctx in
            ctx.cgContext.setFillColor(UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor)
            ctx.cgContext.setStrokeColor(UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor)
            ctx.cgContext.setLineWidth(1)
            
            let rectangle = CGRect(x: 1, y: 1, width: self.frame.height * 0.8, height: self.frame.height * 0.8)
            ctx.cgContext.addEllipse(in: rectangle)
            ctx.cgContext.drawPath(using: .fillStroke)
        }
        circleImageView.image = img
        circleImageView.my_dropShadow()
        initialsLabel.my_dropShadow()
        
    }
    
    @objc func emailTapped() {
        let trimmedLast = last.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: " ", with: "")
   
        let address = "\(first)\(trimmedLast)@<EMAIL>"
        sendEmail(address: address, isFemale: gender, lastName: last)
    }
   

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func sendEmail(address: String, isFemale: Bool, lastName: String) {
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients([address])
            var title = String()
            if isFemale {
                title = "Ms."
            } else {
                title = "Mr."
            }
            mail.setMessageBody("<p>Hello, \(title) \(lastName), <br><br><br> <br>Sincerely,</p>", isHTML: true)
          self.parentViewController?.present(mail, animated: true)
        } else {
            
        }
    }
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
       self.parentViewController?.dismiss(animated: true)
    }
    
}
<file_sep>//
//  my_schoolTime.swift
//  PHS App
//
//  Created by <NAME> on 10/22/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

extension Date {
    func timeOfSchoolDay() -> relativeTime? {
        if self.isSchoolDay() {
            let type = getDayType(date: self)
            let startTime = my_getSchedule(type: type, date: self)!.first!
            let endTime = my_getSchedule(type: type, date: self)!.last!
            if self.localTime() < startTime {
               return .before
            } else if self.localTime() > endTime {
                return .after
            } else {
                return .during
            }
        } else {
            return nil
            
        }
    }
}
<file_sep>//
//  my_getStartEndTimeFromToday.swift
//  PHS App
//
//  Created by <NAME> on 7/31/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation


func my_getStartEndTimeFromToday(type: Int, dayType: dayType, date: Date?) -> [Date] {
    switch type {
    case 0:
        return defaultDaysStartEnd(dayType: dayType, date: date)
        
    case 1, 2, 3, 4, 11, 13, 14, 17, 18, 19, 21:
        return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30)]
    case 5, 6:
        return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 12, minute: 29)]
    case 7:
         return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 11, minute: 00)]
    case 8, 9, 10:
        return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 12, minute: 28)]
    case 15:
        return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 12, minute: 10)]
    case 12, 16:
        return [DateFromTime(hour: 8, minute: 30), DateFromTime(hour: 15, minute: 30)]
    case 20:
        return [Date()]
    case 22, 24, 25, 27:
        //8 am start regular
        return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30) ]
    case 23, 26, 28:
        //8:30 am start regular
        return [DateFromTime(hour: 8, minute: 30), DateFromTime(hour: 15, minute: 30) ]
    case 29:
        return [DateFromTime(hour: 10, minute: 30), DateFromTime(hour: 15, minute: 30)]
    
    default:
        return defaultDaysStartEnd(dayType: dayType, date: date)
    }
}



func defaultDaysStartEnd(dayType: dayType, date: Date?) -> [Date] {
    var weekday = Int()
    switch dayType {
    case .today:
        weekday = Calendar.current.component(.weekday, from: Date())
    case .tomorrow:
         weekday = Calendar.current.component(.weekday, from: Date()) + 1
    case .nextMonday:
        weekday = 0
    case .custom:
        weekday = Calendar.current.component(.weekday, from: date!)
        
    }
    switch weekday {

    case 1, 2, 7, 4, 5:
        return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30)]
    case 3, 6:
       return [DateFromTime(hour: 8, minute: 30), DateFromTime(hour: 15, minute: 30)]

    default:
        return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30)]
    }
}



func DateFromTime(hour: Int, minute: Int) -> Date {
    var dateComponents = DateComponents()
    dateComponents.timeZone = Calendar.current.timeZone
    dateComponents.year = Calendar.current.component(.year, from: Date().noon)
    dateComponents.month = Calendar.current.component(.month, from: Date().noon)
    dateComponents.day = Calendar.current.component(.day, from: Date().noon)
    
   
    
    dateComponents.hour = hour + UTCDifference()
  
    dateComponents.minute = minute
    
   
    
    let userCalendar = Calendar.current
    
    if let milDate = userCalendar.date(from: dateComponents)?.timeIntervalSince1970 {
        return Date(timeIntervalSince1970: milDate)

    }
    
    
    
   return Date()
}

<file_sep>//
//  Today+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/8/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension Today {

    @nonobjc public class func createFetchRequest() -> NSFetchRequest<Today> {
        return NSFetchRequest<Today>(entityName: "Today")
    }

    @NSManaged public var todayType: Int32
    @NSManaged public var tomorrowType: Int32
    @NSManaged public var nextMondayType: Int32
    @NSManaged public var day: Int32

}
<file_sep>//
//  GradeCollectionViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class GradeCollectionViewCell: UICollectionViewCell {
    var label = UILabel()
    var circle = UIView()
    
}
<file_sep>//
//  File.swift
//  PHS App
//
//  Created by <NAME> on 8/4/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit

extension UIView {
    func viewFadeIn() {
        UIView.animate(withDuration: 0.5) {
            self.alpha = 1
        }
    }
    func viewFadeOut() {
        UIView.animate(withDuration: 0.5) {
            self.alpha = 0
        }
    }
}
<file_sep>//
//  PickClassesViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/19/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreData

class PickClassesViewController: UIViewController {
    @IBOutlet weak var prevButton: UIButton!
    @IBAction func prevTapped(_ sender: Any) {
        let _ = navigationController?.popViewController(animated: true)
    }
    @IBOutlet weak var yourClasses: UILabel!
    @IBOutlet weak var p1Label: UILabel!
    @IBOutlet weak var p2Label: UILabel!
    @IBOutlet weak var p3Label: UILabel!
    @IBOutlet weak var p4Label: UILabel!
    @IBOutlet weak var p5Label: UILabel!
    @IBOutlet weak var p6Label: UILabel!
    @IBOutlet weak var p7Label: UILabel!
    @IBOutlet weak var p8Label: UILabel!
    @IBOutlet weak var p1Button: UIButton!
    @IBOutlet weak var p2Button: UIButton!
    @IBOutlet weak var p3Button: UIButton!
    @IBOutlet weak var p4Button: UIButton!
    @IBOutlet weak var p5Button: UIButton!
    @IBOutlet weak var p6Button: UIButton!
    @IBOutlet weak var p7Button: UIButton!
    @IBOutlet weak var p8Button: UIButton!
   
    @IBOutlet weak var p1ClassLabel: UILabel!
    @IBOutlet weak var p2ClassLabel: UILabel!
    @IBOutlet weak var p3ClassLabel: UILabel!
    @IBOutlet weak var p4ClassLabel: UILabel!
    @IBOutlet weak var p5ClassLabel: UILabel!
    @IBOutlet weak var p6ClassLabel: UILabel!
    @IBOutlet weak var p7ClassLabel: UILabel!
    @IBOutlet weak var p8ClassLabel: UILabel!
    @IBAction func p1ButtonTapped(_ sender: Any) {
        period = 1
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBAction func p2ButtonTapped(_ sender: Any) {
        period = 2
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBAction func p3ButtonTapped(_ sender: Any) {
        period = 3
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBAction func p4ButtonTapped(_ sender: Any) {
        period = 4
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBAction func p5ButtonTapped(_ sender: Any) {
        period = 5
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBAction func p6ButtonTapped(_ sender: Any) {
        period = 6
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBAction func p7ButtonTapped(_ sender: Any) {
        period =  7
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBAction func p8ButtonTapped(_ sender: Any) {
        period = 8
        performSegue(withIdentifier: "pickClass", sender: nil)

    }
    @IBOutlet weak var skipButton: UIButton!
    @IBOutlet weak var nextButton: UIButton!
    @IBAction func skipTapped(_ sender: Any) {
        if isFreshLaunch {
            let ac = UIAlertController(title: "Skip this page?", message: "Entering your classes can make the app experiences more personalized.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { (_) in
                for label in self.classLabels {
                    label.text = "SELECT CLASS"
                }
                self.performSegue(withIdentifier: "classSkipped", sender: nil)
            }))
            ac.addAction(UIAlertAction(title: "Stay", style: .cancel))
            present(ac, animated: true)
        } else {
            dismiss(animated: true)
        }
        
    }
    @IBAction func nextTapped(_ sender: Any) {
        if periods.contains(nil) {
            let ac = UIAlertController(title: "Missing Classes", message: "Make sure you fill in all your classes before continuing.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .cancel))
                present(ac, animated: true)
        } else {
            if isFreshLaunch {
                self.performSegue(withIdentifier: "nextToTeacher", sender: nil)
            } else {
                if isPageEditing {
                    self.performSegue(withIdentifier: "editToTeacher", sender: nil)
                } else {
                    self.performSegue(withIdentifier: "classToTeacher", sender: nil)
                }
            }
        }
    }
    
    
    
    var isFreshLaunch = true
    var isPrevButtonHidden = false
    var isPageEditing = false
    var mySelectedTeachers = [MyNewTeachers]()
    var myClasses = [String?]()
    
    
    var buttons = [UIButton]()
    var labels = [UILabel]()
    var classLabels = [UILabel]()
  
    var periods = [String?]()
 
    override var prefersHomeIndicatorAutoHidden: Bool {
        return true
    }
    
    
    func autoResizeUI() {
        prevButton.titleLabel!.font = prevButton.titleLabel!.font.withSize(CGFloat(15).relativeToWidth)
        yourClasses.font = yourClasses.font.withSize(CGFloat(25).relativeToWidth)
        for label in labels {
            label.font = label.font.withSize(CGFloat(25).relativeToWidth)
        }
        for label in classLabels {
            label.font = label.font.withSize(CGFloat(24).relativeToWidth)
        }

    }
    
    
    var period = Int()
   
    
    func createArrays() {
       
        buttons.append(p1Button)
        buttons.append(p2Button)
        buttons.append(p3Button)
        buttons.append(p4Button)
        buttons.append(p5Button)
        buttons.append(p6Button)
        buttons.append(p7Button)
        buttons.append(p8Button)
        labels.append(p1Label)
        labels.append(p2Label)
        labels.append(p3Label)
        labels.append(p4Label)
        labels.append(p5Label)
        labels.append(p6Label)
        labels.append(p7Label)
        labels.append(p8Label)
        classLabels.append(p1ClassLabel)
        classLabels.append(p2ClassLabel)
        classLabels.append(p3ClassLabel)
        classLabels.append(p4ClassLabel)
        classLabels.append(p5ClassLabel)
        classLabels.append(p6ClassLabel)
        classLabels.append(p7ClassLabel)
        classLabels.append(p8ClassLabel)
        if !isPageEditing {
            for _ in 0...7 {
                periods.append(nil)
            }
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createArrays()
        autoResizeUI()
        if isPrevButtonHidden {
            prevButton.isHidden = true
        } else {
            prevButton.isHidden = false
        }
        if isPageEditing {
            let scheduleFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest()
            do {
                var request = try PersistentService.context.fetch(scheduleFetchRequest)
                request.sort {$0.period < $1.period}
                print(request.count, "READ HERE")
                for i in 0...7 {
                    classLabels[i].text = request[i].name?.uppercased()
                }
            } catch {
                
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if !isFreshLaunch  {
            skipButton.setTitle("CANCEL", for: .normal)
           
        }
    }


    
    @IBAction func unwindToClass(segue: UIStoryboardSegue) {
        if segue.identifier == "backToClass" {
            let source = segue.source as? PickerViewController
            if source!.selectedItem != nil {
                let label = classLabels[period - 1]
                   label.text = source!.selectedItem?.uppercased()
                periods[period - 1] = source!.selectedItem
           
            }
            
        } else if segue.identifier == "detailBackToClass" {
            let source = segue.source as? DetailPickerViewController
            if source!.selectedItem != nil {
                let label = classLabels[period - 1]
                label.text = source!.selectedItem?.uppercased()
                periods[period - 1] = source!.selectedItem
                
            }
        }
        
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "skipToTeacher" {
            if let vc = segue.destination as? PickTeachersViewController {
                for _ in 0...7 {
                    vc.classes.append(nil)
                }
            }
            
        } else if segue.identifier == "nextToTeacher" {
            if let vc = segue.destination as? PickTeachersViewController {
                vc.classes = periods
            }
        } else if segue.identifier == "classToTeacher" {
            if let vc = segue.destination as? PickTeachersViewController {
                vc.classes = periods
                vc.isFreshLaunch = false
                vc.isSecondScreen = true
            }
        } else if segue.identifier == "editToTeacher" {
            if let vc = segue.destination as? PickTeachersViewController {
                vc.classes = periods
                vc.isPageEditing = true
                vc.isFreshLaunch = false
                vc.isSecondScreen = true
            }
        }
        
    }
   
 

}
<file_sep>//
//  my_isSchoolDay.swift
//  PHS App
//
//  Created by <NAME> on 8/4/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

extension Date {
    func isSchoolDay() -> Bool {
    
        let type = getDayType(date: self)

        if type == 20 {
            return false
        } else {
            if Calendar.current.component(.weekday, from: self) == 7 ||  Calendar.current.component(.weekday, from: self) == 1 {
              
                return false
            } else {
                
                return true
            }
        }
    }
}
<file_sep>//
//  my_getStartEndPeriodLabel.swift
//  PHS App
//
//  Created by <NAME> on 8/1/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func my_getStartEndPeriodLabel(type: Int) -> [Int]? {
    
    switch type {
    case 0:
        return defaultDaysStartEndPeriodLabel()
    case 1:
        //pep assembly odd
        return [1, 9, 9, 11, 13, 3, 3, 12, 5, 5, 13, 7, 7]
    case 2:
        //pep assembly even
        return [2, 9, 9, 11, 13, 4, 4, 12, 6, 6, 13, 8, 8]
    case 3:
        //extended lunch odd
        return [1, 10, 10, 13, 3, 3, 12, 5, 5, 13, 7, 7]
    case 4, 14:
        //extended lunch even and hour of code
        return [2, 9, 9, 13, 4, 4, 12, 6, 6, 13, 8, 8]

    case 5:
        //finals type 1
        return [1, 3, 3, 7, 7]
    case 6:
        //finals type 2
        return [5, 6, 6, 8, 8]
    case 7:
        //finals two periods
        return [2, 4, 4]
    case 8:
        //minimum 1-8
        return [1, 2, 2, 3, 3, 4, 4, 13, 5, 5, 6, 6, 7, 7, 8, 8]
    case 9:
        //conferences odd
        return [1, 3, 3, 13, 5, 5, 7, 7]
    case 10:
        //conferences even
        return [2, 4, 4, 13, 6, 6, 8, 8]
    case 11:
        //PSAT 9
        return [15, 10, 2, 2, 4, 4, 12, 6, 6, 8, 8]
    case 12:
        //PE testing
        return [16, 10, 1, 1, 3, 3, 12, 5, 5, 7, 7]

    case 13:
        //first 2 days of school
        return [9, 1, 1, 2, 2, 3, 3, 13, 4, 4, 5, 5, 12, 6, 6, 7, 7, 8, 8]
    
    case 15:
        //Passion Day
        return [9, 19, 19, 13, 20, 20, 21, 21]
    case 16:
        //Pre Testing
        return [1, 9, 9, 13, 2, 2, 3, 3, 12, 5, 5, 7, 7]
    case 17:
        //Testing
        return [23, 10, 4, 4, 12, 6, 6, 8, 8]
    case 18:
        //CAASPP odd
        return [24, 13, 10, 10, 1, 1, 3, 3, 12, 5, 5, 7, 7]
    case 19:
        //CAASPP even
        return [24, 13, 10, 10, 2, 2, 4, 4, 12, 6, 6, 8, 8]
    case 20:
        //NO SCHOOL
        return nil
    case 21:
        //fine arts assembly
        return [2, 13, 14, 14, 12, 6, 6, 13, 8, 8]
    case 22:
        //monday schedule
        return [1, 2, 2, 3, 3, 13, 4, 4, 5, 5, 12, 6, 6, 7, 7, 8, 8]
    case 23:
        //tuesday schedule
        return [1, 9, 9, 13, 3, 3, 12, 5, 5, 13, 7, 7]
    case 24:
        //wednesday schedule
        return [2, 10, 13, 4, 4, 12, 6, 6, 13, 8, 8]
    case 25:
        //thursday schedule
        return [1, 10, 13, 3, 3, 12, 5, 5, 13, 7, 7]
    case 26:
        //friday schedule
        return [2, 9, 9, 13, 4, 4, 12, 6, 6, 13, 8, 8]
    case 27:
        //Thursday advisement
         return [1, 9, 13, 3, 3, 12, 5, 5, 13, 7, 7]
    case 28:
        //Friday OH
         return [2, 10, 10, 13, 4, 4, 12, 6, 6, 13, 8, 8]
    case 29:
        return [1, 3, 3, 12, 5, 5, 7, 7]
    default:
        return defaultDaysStartEndPeriodLabel()
    }
}

func defaultDaysStartEndPeriodLabel() -> [Int]? {
    switch Calendar.current.component(.weekday, from: Date()) {
    case 1, 7:
        return nil
    case 2:
        return [1, 2, 2, 3, 3, 13, 4, 4, 5, 5, 12, 6, 6, 7, 7, 8, 8]
    case 3:
        return [1, 9, 9, 13, 3, 3, 12, 5, 5, 13, 7, 7]
    case 4:
        return [2, 10, 13, 4, 4, 12, 6, 6, 13, 8, 8]
    case 5:
        return [1, 10, 13, 3, 3, 12, 5, 5, 13, 7, 7]
    case 6:
        return [2, 9, 9, 13, 4, 4, 12, 6, 6, 13, 8, 8]
    default: return nil
    }
}
<file_sep>//
//  MyNewTeachers+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 1/6/19.
//  Copyright © 2019 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(MyNewTeachers)
public class MyNewTeachers: NSManagedObject {
    //test commit
}
<file_sep>//
//  NameInputViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import TextFieldEffects
import CoreData

class NameInputViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextFieldDelegate, UIGestureRecognizerDelegate {
    
    @IBOutlet weak var skipButton: UIButton!
    @IBOutlet weak var yourName: UILabel!
    @IBOutlet weak var yourGrade: UILabel!
    @IBOutlet weak var yourHouse: UILabel!
    @IBOutlet weak var gradeCollectionView: UICollectionView!
    @IBOutlet weak var houseCollectionView: UICollectionView!
    @IBOutlet weak var firstName: HoshiTextField!
    @IBOutlet weak var lastName: HoshiTextField!
    @IBAction func nextTapped(_ sender: Any) {
        if first != nil && last != nil && grade != nil && house != nil {
            if isFreshLaunch {
                performSegue(withIdentifier: "nextToID", sender: nil)

            } else {
                if isPageEditing {
                    performSegue(withIdentifier: "editingToID", sender: nil)
                } else {
                    performSegue(withIdentifier: "nameToID", sender: nil)

                }
            }
        } else {
           
            let ac = UIAlertController(title: "Missing Fields", message: "Some fields are empty, make sure they are filled in in order to continue.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .cancel))
            present(ac, animated: true)
        }
    }
    @IBAction func skipTapped(_ sender: Any) {
        if isFreshLaunch {
            let ac = UIAlertController(title: "Skip this page?", message: "Entering general information about yourself can make the app experience more personalized.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { _ in
                self.performSegue(withIdentifier: "skipToID", sender: nil)
            }))
            ac.addAction(UIAlertAction(title: "Stay", style: .cancel))
            present(ac, animated: true)
        } else {
           dismiss(animated: true)
        }
      
    }
    var first: String?
    var last: String?
    var grade: Int?
    var house: String?
    var longID: String?
    var shortID: String?
    
   var gradeArray = [9, 10, 11, 12]
    var houseArray = ["Hercules", "Orion", "Pegasus", "Poseidon"]
    var isFreshLaunch = true
    var isPageEditing = false
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "nextToID" {
            let vc = segue.destination as! IDInputViewController
            vc.first = first
            vc.last = last
            vc.house = house
            vc.grade = grade
        } else if segue.identifier == "skipToID" {
            let vc = segue.destination as! IDInputViewController
            vc.first = nil
            vc.last = nil
            vc.house = nil
            vc.grade = nil
        } else if segue.identifier == "nameToID" {
            let vc = segue.destination as! IDInputViewController
            vc.first = first
            vc.last = last
            vc.house = house
            vc.grade = grade
            vc.isFreshLaunch = false
        } else if segue.identifier == "editingToID" {
            let vc = segue.destination as! IDInputViewController
            vc.first = first
            vc.last = last
            vc.house = house
            vc.grade = grade
            vc.shortID = Int(shortID!)
            vc.longID = Int(longID!)
            vc.isFreshLaunch = false
            vc.isPageEditing = true
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  
        if collectionView == gradeCollectionView {
            return 4
        } else if collectionView == houseCollectionView {
            return 4
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == gradeCollectionView {
            return CGSize(width: CGFloat(55).relativeToWidth, height: CGFloat(55).relativeToWidth)
        } else if collectionView == houseCollectionView {
            return CGSize(width: UIScreen.main.bounds.width / 3, height: CGFloat(60).relativeToWidth)
        }
        return CGSize(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == gradeCollectionView {
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "grade", for: indexPath) as!GradeCollectionViewCell
                cell.label.text = "\(gradeArray[indexPath.item])"
            
            cell.label.textAlignment = .center
                cell.label.bounds = CGRect(x: 0, y: 0, width: CGFloat(55).relativeToWidth, height: CGFloat(55).relativeToWidth)
                cell.label.textColor = UIColor.white
                cell.label.font = UIFont(name: "Lato-Light", size: CGFloat(24).relativeToWidth)
                cell.label.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2)
                cell.circle.bounds = CGRect(x: 0, y: 0, width: CGFloat(55).relativeToWidth, height: CGFloat(55).relativeToWidth)
                cell.circle.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2)
                cell.circle.clipsToBounds = true
                cell.circle.layer.cornerRadius = cell.circle.frame.width / 2
                cell.circle.layer.borderColor = UIColor.white.cgColor
            cell.circle.layer.borderWidth = 1.5
                cell.circle.layer.backgroundColor = UIColor.white.withAlphaComponent(0).cgColor
                cell.addSubview(cell.circle)
            cell.addSubview(cell.label)
            print(indexPath.item)
                return cell
                
            
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "house", for: indexPath) as! HouseCollectionViewCell
            cell.label.text = houseArray[indexPath.item].uppercased()
            cell.label.textAlignment = .center
            cell.label.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width / 3, height: CGFloat(55).relativeToWidth)
            cell.label.textColor = UIColor.white
            cell.label.font = UIFont(name: "Lato-Light", size: CGFloat(20).relativeToWidth)
            cell.label.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2)
            cell.roundedRect.bounds = CGRect(x: 0, y: 0, width: CGFloat(120).relativeToWidth, height: CGFloat(50).relativeToWidth)
            cell.roundedRect.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2)
            cell.roundedRect.clipsToBounds = true
            cell.roundedRect.layer.cornerRadius = cell.roundedRect.frame.height / 2
            cell.roundedRect.layer.borderColor = UIColor.white.cgColor
            cell.roundedRect.layer.borderWidth = 1.5
            cell.roundedRect.layer.backgroundColor = UIColor.white.withAlphaComponent(0).cgColor
            cell.addSubview(cell.roundedRect)
             cell.addSubview(cell.label)
          
            return cell
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        let cell = collectionView.cellForItem(at: indexPath)!
        if cell.isSelected {
            collectionView.deselectItem(at: indexPath, animated: true)
           self.collectionView(collectionView, didDeselectItemAt: indexPath)
            if collectionView == gradeCollectionView {
                grade = nil
            } else if collectionView == houseCollectionView {
                house = nil
            }
            return false
        } else {
            return true
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == gradeCollectionView {
            let cell = collectionView.cellForItem(at: indexPath)!
            
                grade = gradeArray[indexPath.item]
                
                if let item = cell as? GradeCollectionViewCell {
                    UIView.animate(withDuration: 0.3) {
                        item.label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
                        item.circle.backgroundColor = UIColor.white.withAlphaComponent(1)
                    }
                    
                }
            
          
        } else {
            let cell = collectionView.cellForItem(at: indexPath)!

                house = houseArray[indexPath.item]
                
                if let item = cell as? HouseCollectionViewCell {
                    UIView.animate(withDuration: 0.3) {
                        item.label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
                        item.roundedRect.backgroundColor = UIColor.white.withAlphaComponent(1)
                        
                    }

            }
            
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        if collectionView == gradeCollectionView {
            let cell = collectionView.cellForItem(at: indexPath)
            
            if let item = cell as? GradeCollectionViewCell {
                UIView.animate(withDuration: 0.3) {
                    item.label.textColor = UIColor.white
                    item.circle.backgroundColor = UIColor.white.withAlphaComponent(0)
                }
                
            }
        } else {
            let cell = collectionView.cellForItem(at: indexPath)
            
            if let item = cell as? HouseCollectionViewCell {
                UIView.animate(withDuration: 0.3) {
                    item.label.textColor = UIColor.white
                    item.roundedRect.backgroundColor = UIColor.white.withAlphaComponent(0)
                    
                }
                
            }
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == firstName {
            if textField.text == "" {
                first = nil
            } else {
                first = textField.text
                firstName.resignFirstResponder()
            }
           
        } else if textField == lastName {
            if textField.text == "" {
                last = nil
            } else {
                last = textField.text
                firstName.resignFirstResponder()
            }
           
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.view.gestureRecognizers?.first!.isEnabled = true
        if textField == lastName {
            first = firstName.text
        } else if textField == firstName {
            last = lastName.text
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == firstName {
            first = textField.text
           firstName.resignFirstResponder()
            self.view.gestureRecognizers?.first!.isEnabled = false
        } else if textField == lastName {
            last = textField.text
            lastName.resignFirstResponder()
            self.view.gestureRecognizers?.first!.isEnabled = false

        }
        return true
    }
    
    

    override var prefersHomeIndicatorAutoHidden: Bool {
    return true
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        firstName.delegate = self
        lastName.delegate = self
        gradeCollectionView.delegate = self
        houseCollectionView.delegate = self
        gradeCollectionView.dataSource = self
        houseCollectionView.dataSource = self 
        gradeCollectionView.backgroundColor = UIColor.white.withAlphaComponent(0)
        houseCollectionView.backgroundColor = UIColor.white.withAlphaComponent(0)
        gradeCollectionView.allowsMultipleSelection = false
        houseCollectionView.allowsMultipleSelection = false
        yourHouse.font = yourHouse.font.withSize(CGFloat(25).relativeToWidth)
        yourName.font = yourHouse.font.withSize(CGFloat(25).relativeToWidth)
        yourGrade.font = yourHouse.font.withSize(CGFloat(25).relativeToWidth)
        
        let gradeLayout = self.gradeCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        gradeLayout.minimumInteritemSpacing = CGFloat(20).relativeToWidth
        gradeLayout.sectionInset = UIEdgeInsets.init(top: 0, left: CGFloat(30).relativeToWidth, bottom: 0, right: CGFloat(30).relativeToWidth)
    
        let houseLayout = self.houseCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        houseLayout.minimumInteritemSpacing = CGFloat(20).relativeToWidth
        houseLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 35, bottom: 0, right: 35)
        houseLayout.minimumLineSpacing = CGFloat(20).relativeToWidth
        
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(screenTapped))
        gestureRecognizer.delegate = self
        view.addGestureRecognizer(gestureRecognizer)
        gestureRecognizer.isEnabled = false
        
        if CheckInternet.Connection() {
            DispatchQueue.global(qos: .background).async {
                if localTeachers.count == 0 {
                    fetchTeachers()
                }
                DispatchQueue.main.async {
                    let fetchRequest: NSFetchRequest<Teachers> = Teachers.fetchRequest()
                    let sort = NSSortDescriptor(key: "last", ascending: true)
                    fetchRequest.sortDescriptors = [sort]
                    do {
                        let newRequest = try PersistentService.context.fetch(fetchRequest)
                        
                        savedTeachers = newRequest
                        if teachersAlphaDict.count == 0 {
                            generateAlphaDict()
                        }
                        if subjectsDictionary.count == 0 {
                            generateSubjectsDict()
                        }
                        
                    } catch {
                        
                    }
                }
            }
        } else {
            let ac = UIAlertController(title: "No Internet Connection", message: "Trouble loading certain data, make sure you are connected to the Internet. You may still continue the set-up process.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .cancel))
            present(ac, animated: true)
        }
      
            
          
        
       
        
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if !isFreshLaunch {
            if isPageEditing {
                firstName.text = first
                lastName.text = last
                gradeCollectionView.selectItem(at: [0, grade! - 9], animated: true, scrollPosition: [])
                self.collectionView(self.gradeCollectionView, didSelectItemAt: [0, grade! - 9])
                
                
                var houseArrayIndex = Int()
                for i in 0...houseArray.count - 1 {
                    if houseArray[i] == house {
                        houseArrayIndex = i
                        break
                    }
                }
                houseCollectionView.selectItem(at: [0, houseArrayIndex], animated: true, scrollPosition: [])
                self.collectionView(self.houseCollectionView, didSelectItemAt: [0, houseArrayIndex])
                
                
            }
        }
    }
    
    @objc func screenTapped() {
        if firstName.isEditing || lastName.isEditing {
            if firstName.text != nil {
                first = firstName.text!
                firstName.resignFirstResponder()
                self.view.gestureRecognizers?.first!.isEnabled = false

            } else {
                firstName = nil
                firstName.resignFirstResponder()
                self.view.gestureRecognizers?.first!.isEnabled = false

            }
            if lastName.text != nil {
              last = lastName.text!
                lastName.resignFirstResponder()
                self.view.gestureRecognizers?.first!.isEnabled = false

            } else {
                lastName = nil
                lastName.resignFirstResponder()
                self.view.gestureRecognizers?.first!.isEnabled = false

            }
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        if isFreshLaunch == false {
            skipButton.setTitle("CANCEL", for: .normal)
            
        }
    }
   
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  User+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension User {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<User> {
        return NSFetchRequest<User>(entityName: "User")
    }

    @NSManaged public var first: String?
    @NSManaged public var last: String?
    @NSManaged public var grade: Int16
    @NSManaged public var house: String?
    @NSManaged public var shortID: Int32
    @NSManaged public var longID: Int32

}
<file_sep>//
//  Games.swift
//  PHS App
//
//  Created by <NAME> on 8/20/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class Games: NSObject {
    var sport = String()
    var other: String?
    var isAway = Bool()
    var time = Date()
    var homeScore: Int?
    var awayScore: Int?
}
<file_sep>//
//  TeacherPickerViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/19/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import PickerView


class TeacherPickerViewController: UIViewController {

    enum ItemsType : Int {
        case label, customView
    }
    
    enum PresentationType {
        case numbers(Int, Int), names(Int, Int)
    }
    
    
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    
    @IBOutlet weak var pickerView: PickerView!
    
    @IBAction func cancelTapped(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func doneTapped(_ sender: Any) {
        if currentSelectedValue != nil {
            selectedItem = currentSelectedValue!
            performSegue(withIdentifier: "backToTeacher", sender: nil)
        }
    }
    
    
    var selectedSubject = String()

    var teacherObjects = [NewTeachers]()
    
    
    var presentationType = PresentationType.numbers(0, 0)
    var selectedItem: NewTeachers?
    var currentSelectedValue: NewTeachers?
    var updateSelectedValue: ((_ newSelectedValue: String) -> Void)?
    
    var itemsType: PickerViewController.ItemsType = .label
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
                configurePicker()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
    }
    
    
    
    fileprivate func configurePicker() {
        pickerView.delegate = self
        pickerView.dataSource = self
        pickerView.scrollingStyle = .default
        pickerView.selectionStyle = .none
        if let currentSelected = currentSelectedValue, let indexOfCurrentSelectedValue = teacherObjects.index(of: currentSelected) {
            pickerView.currentSelectedRow = indexOfCurrentSelectedValue
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */


}

extension TeacherPickerViewController: PickerViewDelegate {
    func pickerViewHeightForRows(_ pickerView: PickerView) -> CGFloat {
        
        return 50.0
    }
    
    func pickerView(_ pickerView: PickerView, styleForLabel label: UILabel, highlighted: Bool) {
        
        label.textAlignment = .center
        if (highlighted) {
            label.font = UIFont(name: "Lato-Light", size: CGFloat(28).relativeToWidth)
            label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
        } else {
            label.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth)
            label.textColor = UIColor.lightGray.withAlphaComponent(0.75)
        }
    }
    
    func pickerView(_ pickerView: PickerView, didSelectRow row: Int, index: Int) {
        
            currentSelectedValue = self.teacherObjects[index]
            
        
    }
}

extension TeacherPickerViewController: PickerViewDataSource {
    func pickerView(_ pickerView: PickerView, titleForRow row: Int) -> String {
        return ""
    }
    
    func pickerViewNumberOfRows(_ pickerView: PickerView) -> Int {
        
        return teacherObjects.count
    }
    
    func pickerView(_ pickerView: PickerView, titleForRow row: Int, index: Int) -> String {
        
        return "\(teacherObjects[index].first) \(teacherObjects[index].last)"
    }
    
    
}
<file_sep>//
//  CalendarCollectionViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/21/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import JTAppleCalendar


class CalendarCollectionViewCell: JTAppleCell {
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var selectedView: UIView!
    @IBOutlet weak var dotView: UIView!
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
}
<file_sep>//
//  my_numberToLabel.swift
//  PHS App
//
//  Created by <NAME> on 8/2/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import CoreData

func myClassArray() -> [String?] {
    var classes = [String]()
    let classFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest()
    do {
        var request = try PersistentService.context.fetch(classFetchRequest)
        if request.count > 0 {
            request.sort {$0.period < $1.period}
            for i in 0...7 {
                classes.append(request[i].name!)
            }
        } else {
            classes = []
        }
       
    } catch {
        
    }
    return classes
}

extension Int {
    func getPeriodLabel() -> String {
       
        switch self {
        case 1:
            if myClassArray().count == 0 {
                return "PERIOD 1"
            } else {
               
                return myClassArray()[0]?.uppercased() ?? "PERIOD 1"
            }
        case 2:
            if myClassArray().count == 0 {
                return "PERIOD 2"
            } else {
                 return myClassArray()[1]?.uppercased() ?? "PERIOD 2"
            }
        case 3:
            if myClassArray().count == 0 {
                return "PERIOD 3"
            } else {
                return myClassArray()[2]?.uppercased() ?? "PERIOD 3"

            }
        case 4:
            if myClassArray().count == 0 {
                return "PERIOD 4"
            } else {
                return myClassArray()[3]?.uppercased() ?? "PERIOD 4"

            }
        case 5:
            if myClassArray().count == 0 {
                return "PERIOD 5"
            } else {
                return myClassArray()[4]?.uppercased() ?? "PERIOD 5"

            }
        case 6:
            if myClassArray().count == 0 {
                return "PERIOD 6"
            } else {
                return myClassArray()[5]?.uppercased() ?? "PERIOD 6"

            }
        case 7:
            if myClassArray().count == 0 {
                return "PERIOD 7"
            } else {
                return myClassArray()[6]?.uppercased() ?? "PERIOD 7"

            }
        case 8:
            if myClassArray().count == 0 {
                return "PERIOD 8"
            } else {
                return myClassArray()[7]?.uppercased() ?? "PERIOD 8"

            }
        case 9:
            return "ADVISEMENT"
        case 10:
            return "OFFICE HOURS"
        case 11:
            return "PEP ASSEMBLY"
        case 12:
            return "LUNCH"
        case 13:
            return "BREAK"
        case 14:
            return "ASSEMBLY / PERIOD 4"
        case 15:
            return "PSAT"
        case 16:
            return "PE TESTING 9"
        case 17:
            return "ADVISEMENT / THEATE"
        case 18:
            return "THEATRE / ADVISEMENT"
        case 19:
            return "SESSION 1"
        case 20:
            return "SESSION 2"
        case 21:
            return "SESSION 3"
        case 22:
            return "SESSION 4"
        case 23:
            return "10-11 TESTING"
        case 24:
            return "JUNIORS TESTING"
        default: return ""
        }
    }
}

//1-8: PERIOD 1-8
//9: Advisement
//10: Office Hours
//11: Pep Assembly
//12: Lunch
//13: Break
//14: Assembly / PERIOD 4
//15: PSAT 9
//16: PE Testing 9
//17: Advisement / Theatre
//18: Theatre / Advisement
//19: SESSION 1
//20: SESSION 2
//21: SESSION 3
//22: SESSION 4
//23: 10-11 Testing
//24: 11 Testing
<file_sep>//
//  UnderConstructionViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreGraphics
import MessageUI

class UnderConstructionViewController: UIView {
    @IBOutlet weak var underConstructionLabel: UILabel!
    @IBOutlet weak var bottomLabel: UILabel!
    var buttonView = UIView()
    var buttonLabel = UILabel()
   
       
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  HomeViewController.swift
//  PHS App
//
//  Created by <NAME> on 7/22/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreGraphics
import UserNotifications

enum dayType {
    case today
    case tomorrow
    case nextMonday
    case custom
}

     var specialDays = [SpecialDays]()

    var today = Int()
    var tomorrow = Int()
    var nextMonday = Int()

func getDayType(date: Date) -> Int {
   
    var isSpecial = false
    for days in specialDays {
        if days.date.noon == date.noon {
            isSpecial = true
      
            return Int(days.type)
        }
    }
    if isSpecial == false {
        return 0
    }
    
}

func loadSpecialDays() {
    
    if let data = Bundle.main.path(forResource: "specialDays", ofType: "txt") {
       
        if let content = try? String(contentsOfFile: data) {
            
            if let jsonData = JSON(parseJSON: content).dictionaryValue["specialDays"]?.arrayValue {
                
                for days in jsonData {
                   
                    
                    let detail = days.dictionaryObject!
                    let object = SpecialDays()
                    if let date = detail["date"] as? String {
                        let formatter = DateFormatter()
                        formatter.dateFormat = "yyyy/M/dd"
                        formatter.timeZone = Calendar.current.timeZone
                        formatter.locale = Calendar.current.locale
                        object.date = formatter.date(from: date)!
                    }
                    if let type = detail["case"] as? Int {
                        object.type = type
                    }
                
                    specialDays.append(object)
                }
            }
            
        }
    }
  
}

class HomeViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var showMoreButton: UIButton!
    @IBAction func buttonTapped(_ sender: Any) {
        UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (notif) in
            
        })
        UNUserNotificationCenter.current().getDeliveredNotifications { (notifDel) in
            
        }
        

    }
    
    
    @IBOutlet weak var timeLeftLabel: UILabel!
    @IBOutlet weak var endsLabel: UILabel!
    @IBOutlet weak var minutesLabel: UILabel!
   
    var weekdayLabelView  = UIView()
    var barImage = UIView()
    var weekdayDots = UIView()
    var progressBar = UIView()
    var todayClassLabel = UIView()
    var day = Calendar.current.component(.day, from: Date())
    var minute = Calendar.current.component(.minute, from: Date())
    var timeOfDay: relativeTime?
    
    var schoolEvents = [SchoolEvents]()
    
    let joinButton = UIView()
    let joinLabel = UILabel()
    
    var deviceAnchor6 = Int()
    var deviceMax = Int()
    var eventTimes = [String]()
    var eventTitles = [String]()
    
    var isAppOpenedByUser = false
    var isAppConnected = false
    var fetchedNumber = Int()
    var savedEvents = [SavedEvents]()
    
    var timer: Timer? = nil
    
    
    @IBOutlet weak var eventTime1: UILabel!
    @IBOutlet weak var eventTitle1: UILabel!
    @IBOutlet weak var eventTime2: UILabel!
    @IBOutlet weak var eventTitle2: UILabel!
    @IBOutlet weak var eventTime3: UILabel!
    @IBOutlet weak var eventTitle3: UILabel!
    @IBOutlet weak var gradient: UIImageView!
    @IBOutlet weak var background: UIImageView!
    
    var labels = [UILabel]()
    var views = [UIView]()
    var eventLabels = [UILabel]()
    
    let lastDay = Date(timeIntervalSince1970: 1559977200)
    let firstDay2019 = Date(timeIntervalSince1970: 1566457200)
    var dateDifference = Int()
    
    @objc func timeTapped() {
        timeLeftLabel.my_glowOnTap()
        minutesLabel.my_glowOnTap()
        endsLabel.my_glowOnTap()
    }
    @objc func event1Tapped() {
        eventTitle1.my_glowOnTap()
        eventTime1.my_glowOnTap()
    }
    @objc func event2Tapped() {
        eventTitle2.my_glowOnTap()
        eventTime2.my_glowOnTap()
    }
    @objc func event3Tapped() {
        eventTitle3.my_glowOnTap()
        eventTime3.my_glowOnTap()
    }
    
    func startTimer() {
    
        if timer == nil {
          
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
        }
    }
    
    func stopTimer() {
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
    
    func initialize() {
        deviceAnchor6 = Int(self.view.bounds.maxX / 6)
        deviceMax = Int(self.view.bounds.maxX)
        timeLeftLabel.my_dropShadow()
        endsLabel.my_dropShadow()
        minutesLabel.my_dropShadow()
        labels = [endsLabel, minutesLabel, timeLeftLabel, eventTime1, eventTime2, eventTime3, eventTitle1, eventTitle2, eventTitle3]
        views = [weekdayLabelView, weekdayDots, progressBar, barImage, todayClassLabel]
        eventLabels = [eventTime1, eventTime2, eventTime3, eventTitle1, eventTitle2, eventTitle3]
        
        for label in labels {
            label.alpha = 0
            label.font = label.font.withSize(label.font.pointSize.relativeToWidth)
            
        }
        for view in views {
            view.alpha = 0
        }
        for label in eventLabels {
        label.text = " "
        }
        let timeGesture = UITapGestureRecognizer(target: self, action: #selector(timeTapped))
        let event1Gesture = UITapGestureRecognizer(target: self, action: #selector(event1Tapped))
        let event2Gesture = UITapGestureRecognizer(target: self, action: #selector(event2Tapped))
        let event3Gesture = UITapGestureRecognizer(target: self, action: #selector(event3Tapped))
        timeGesture.delegate = self
        event1Gesture.delegate = self
        event2Gesture.delegate = self
        event3Gesture.delegate = self
        timeLeftLabel.addGestureRecognizer(timeGesture)
        eventTime1.addGestureRecognizer(event1Gesture)
        eventTitle1.addGestureRecognizer(event1Gesture)
        eventTime2.addGestureRecognizer(event2Gesture)
        eventTitle2.addGestureRecognizer(event2Gesture)
        eventTime3.addGestureRecognizer(event3Gesture)
        eventTitle3.addGestureRecognizer(event3Gesture)
        showMoreButton.titleLabel!.font = showMoreButton.titleLabel!.font.withSize(showMoreButton.titleLabel!.font.pointSize.relativeToWidth.relativeToWidth)
        showMoreButton.imageEdgeInsets.left = showMoreButton.imageEdgeInsets.left.relativeToWidth.relativeToWidth
        showMoreButton.isHidden = true
    }
  
    func fadeInViews(isAppOpened: Bool, completion: () -> ()) {
        DispatchQueue.main.async {
           
            self.timeOfDay = Date().timeOfSchoolDay()
            self.fetchEvents()
            self.configureWeekdays()
                if Date() >= Date.init(timeIntervalSince1970: 1552806000) {
           // self.configureWeekdayDots()
            }
            self.configureProgressBar()
            self.configureBar()
            self.configureBarLabel(type: today)
            self.configureTimeLeftLabel()
        }
        completion()
    }
    
    func startAnimation() {
        
        DispatchQueue.main.async {
            UIView.animate(withDuration: 0.3, delay: 0.1, animations: {
                self.weekdayLabelView.alpha = 1
                self.weekdayDots.alpha = 1
                self.joinButton.alpha = 1
            })
            UIView.animate(withDuration: 0.3, delay: 0.1, animations: {
                self.progressBar.alpha = 1
                self.barImage.alpha = 1
                self.todayClassLabel.alpha = 1
                
            })
            
            UIView.animate(withDuration: 0.3, delay: 0.1, animations: {
                self.eventTime1.alpha = 1
                self.eventTitle1.alpha = 1
                
            })
            UIView.animate(withDuration: 0.3, delay: 0.1, animations: {
                self.eventTime2.alpha = 1
                self.eventTitle2.alpha = 1
                
            })
            UIView.animate(withDuration: 0.3, delay: 0.1, animations: {
                self.eventTime3.alpha = 1
                self.eventTitle3.alpha = 1
                
            })
            UIView.animate(withDuration: 0.3, delay: 0.1, animations: {
                self.showMoreButton.alpha = 1
            })
            
        }
    }
    
    func userDefaults() {
        //first launch
//        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
//        if !launchedBefore {
//            UserDefaults.standard.set(true, forKey: "launchedBefore")
//            self.performSegue(withIdentifier: "welcome", sender: nil)
//        }
        
        
        //local notification patch
        let ifNotifUpdated = UserDefaults.standard.bool(forKey: "updateNotification")
        if !ifNotifUpdated {
            UserDefaults.standard.set(true, forKey: "notificationScheduled")
            UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (request) in
                if request.count > 0 {
                    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
                }
            })
        }
        
        //teacher local migration notification
//        let isTeacherUpdated = UserDefaults.standard.bool(forKey: "updateTeacher")
//        if !isTeacherUpdated {
//            UserDefaults.standard.set(true, forKey: "updateTeacher")
//            let ac = UIAlertController(title: "Fill in your Schedule", message: "Over break, we have rebuilt the teachers page in order to optimize battery usage. As a result, we had to erase your saved classes and teachers. Head over to the teachers page to fill out your schedule again for a more personal experience.", preferredStyle: .alert)
//            ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
//            present(ac, animated: true)
//        }
    
     
    }
    
    func launchIntegral() {
           UIApplication.shared.open(URL(string: "https://apps.apple.com/us/app/integral-digital-backpack/id1480096639")!, options: [:], completionHandler: nil)
    }
 
    override func viewDidLoad() {
        super.viewDidLoad()
        tabBarController?.tabBar.isHidden = true
        //lay out UI
        initialize()
        
        

            //set-up
            isAppConnected = CheckInternet.Connection()
            loadSpecialDays()
            scheduleNotifications()
            getTodayType()
            DispatchQueue.global(qos: .background).async {
                
                //User Defaults
                self.userDefaults()
                self.fadeInViews(isAppOpened: self.isAppOpenedByUser, completion: {
                    self.startAnimation()
                })
            }
            
            
            
            //initilize timer
            startTimer()
        
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)

        //change status bar color
    
        
        //continue application
        if Date().isSchoolDay() {
            if Date().getRelativeTime() == relativeTime.during {
                fetchTimeLeft()
            }
        }
      
        
            self.joinButton.backgroundColor = UIColor.clear
            self.joinLabel.textColor = UIColor.white
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        //stop the timer
    
    }
    
    

    func scheduleLocal(on date: Date, with type: Int) {
        let notificationDate = Calendar.current.date(byAdding: .day, value: -1, to: date)!
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                if date.isLongBreak == false {
                    var dateComponents = DateComponents()
                    dateComponents.year = Calendar.current.component(.year, from: notificationDate)
                    dateComponents.month = Calendar.current.component(.month, from: notificationDate)
                    dateComponents.day = Calendar.current.component(.day, from: notificationDate)
                    dateComponents.hour = 20
                    dateComponents.minute = 0
                    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
                    let content = UNMutableNotificationContent()
                    content.title = "Schedule Reminder"
                    content.body = my_notificationPrompt(type: type)
                    content.sound = UNNotificationSound.default
                    
                    
                    let request = UNNotificationRequest(identifier: "\(date.noon)\(type)", content: content, trigger: trigger)
                    center.add(request)
                }
              
            } else {
               
            }
        }
    }

    

   
    
    func getTodayType() {
        today = 0
        tomorrow = 0
        nextMonday = 0
        for days in specialDays {
          
            if Date().noon == days.date.noon {
            
                today = days.type
               
            
            }
            if Date().tomorrow == days.date.noon {
                tomorrow = days.type
            
            }
            if Date().nextMonday().noon == days.date.noon {
                nextMonday = days.type
                
            }
        }
    
    }
    
    func scheduleNotifications() {
        var reducedSpecialDays = [SpecialDays]()
   
        reducedSpecialDays = specialDays.filter { $0.date > Date() }
        
        for days in reducedSpecialDays {
            scheduleLocal(on: days.date, with: days.type)
        }
        
        
    }
    
    
    @objc func update() {
       
        
       /*
        if isAppConnected == false {
            if CheckInternet.Connection() {
                updateWhenFirstConnected()
                isAppConnected = true
            }
        }*/
                
        if Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .during {
            fetchTimeLeft()
        } else {
            //update only at midnight
            if Calendar.current.component(.day, from: Date()) != day {
                if Date() > lastDay && Date() < firstDay2019 {
                    dateDifference = Calendar.current.dateComponents([.day], from: firstDay2019, to: Date()).day ?? 0
                    loadTimeLeftLabel(text: String(dateDifference), size: CGFloat(140))
                } else {
                    updateAtMidNight()
                    day = Calendar.current.component(.day, from: Date())
                }
            } else {
                if Date() > lastDay && Date() < firstDay2019 {
                    //nothing happens
                } else {
                    if timeOfDay != Date().getRelativeTime() {
                        timeOfDay = Date().timeOfSchoolDay()
                        if (Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .after) {
                            dateDifference = Calendar.current.dateComponents([.day], from: Date(), to: firstDay2019).day ?? 0
                            loadTimeLeftLabel(text: String(dateDifference), size: CGFloat(140))
                            loadMinutesLabel(text: "DAYS")
                            loadEndsLabel(text: "SCHOOL STARTS IN")
                        } else {
                            self.configureTimeLeftLabel()
                        }
                    } else {
                        if minute != Calendar.current.component(.minute, from: Date()) {
                            if Date().isSchoolDay() {
                                
                                if timeOfDay == .during {
                                    
                                    loadProgressingBar(isInitial: false)
                                }
                            }
                            if Date().isSchoolDay() {
                                if timeOfDay == .during {
                                    fetchTimeLeft()
                                }
                            }
                            minute = Calendar.current.component(.minute, from: Date())
                        }
                    }
                    
                }
            }
            
        }
        
       
    }
    
  
  
    
    func updateWhenFirstConnected() {
        fetchEvents()
    }
    
    
    func updateAtMidNight() {
        
        eventTimes.removeAll()
        eventTitles.removeAll()
        savedEvents.removeAll()
        getTodayType()
        timeOfDay = Date().timeOfSchoolDay()
            configureTimeLeftLabel()
            for subview in weekdayDots.subviews {
                subview.removeFromSuperview()
            }
        if Date() >= Date.init(timeIntervalSince1970: 1552806000) {
            configureWeekdayDots()
        }
        
            progressBar.removeFromSuperview()
            configureProgressBar()
            progressBar.viewFadeIn()
            view.bringSubviewToFront(barImage)
            for subviews in todayClassLabel.subviews {
                subviews.removeFromSuperview()
            }
            configureBarLabel(type: today)
            fetchEvents()
 
    }

    @objc func joinTapped() {
//        UIView.animate(withDuration: 0.3) {
//
//        }
//        UIView.animate(withDuration: 0.3, animations: {
//            self.joinButton.backgroundColor = UIColor.white
//            self.joinLabel.textColor = UIColor(red: 0.702, green: 0.667, blue: 0.843, alpha: 1.00)
//        }) { (_) in
//            UIView.animate(withDuration: 0.2, delay: 0.5, animations: {
//                self.joinButton.backgroundColor = UIColor.clear
//                self.joinLabel.textColor = UIColor.white
//            }, completion: nil)
//        }
//        if let vc = storyboard?.instantiateViewController(withIdentifier: "join") as? JoinViewController {
//            present(vc, animated: true)
//        }
//
      UIApplication.shared.open(URL(string: "https://apps.apple.com/us/app/integral-digital-backpack/id1480096639")!, options: [:], completionHandler: nil)
    }
    
    
    func configureWeekdays() {
       
            joinButton.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width / 1.5, height: self.view.bounds.width / 6)
            joinButton.center = CGPoint(x: self.view.bounds.midX, y: self.minutesLabel.center.y + CGFloat(70).relativeToWidth)
            joinButton.layer.borderColor = UIColor.white.cgColor
            joinButton.layer.borderWidth = 2
            joinButton.layer.cornerRadius = joinButton.bounds.height / 2
            joinButton.clipsToBounds = true
            view.addSubview(joinButton)
            joinLabel.bounds = joinButton.bounds
            joinLabel.center = CGPoint(x: joinButton.bounds.width / 2, y: joinButton.bounds.height / 2)
            joinLabel.textAlignment = .center
            joinLabel.textColor = UIColor.white

        joinLabel.attributedText = NSAttributedString(string: "DOWNLOAD INTEGRAL", attributes:
            [.underlineStyle: NSUnderlineStyle.single.rawValue])
            joinLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(18).relativeToWidth)
            joinButton.addSubview(joinLabel)
            let joinGesture = UITapGestureRecognizer(target: self, action: #selector(joinTapped))
            joinGesture.delegate = self
            joinButton.addGestureRecognizer(joinGesture)
            joinButton.alpha = 0
            
        
//        else {
//                    for i in 0...4 {
//                        let weekdayLabels = ["M", "T", "W", "T", "F"]
//                        let weekdayLabel = UILabel()
//                        weekdayLabel.frame = CGRect(x: 0, y: 0, width: 21, height: 21)
//                        weekdayLabel.center = CGPoint(x: deviceAnchor6 + deviceAnchor6 * i, y: Int(self.view.bounds.midY) - Int(CGFloat(30).relativeToWidth))
//                        weekdayLabel.textAlignment = .center
//                        weekdayLabel.text = weekdayLabels[i]
//                        weekdayLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(17).relativeToWidth)
//                        weekdayLabel.textColor = UIColor.white
//                        weekdayLabel.my_dropShadow()
//                        weekdayLabelView.addSubview(weekdayLabel)
//
//                    }
//                    view.addSubview(weekdayLabelView)
//        }


    }

    func configureWeekdayDots() {
        for i in 0 ... 4 {
             drawDots(withFill: false, loopNumber: i)
        }
         let weekToday = Calendar.current.component(.weekday, from: Date())
        if weekToday == 1 {
            view.addSubview(weekdayDots)
        } else if weekToday == 6  || weekToday == 7 {
         for i in 0...4 {
         drawDots(withFill: true, loopNumber: i)
            view.addSubview(weekdayDots)
            }
         } else {
         for i in 0...(weekToday - 2) {
         drawDots(withFill: true, loopNumber: i)
            view.addSubview(weekdayDots)
         }

         }
        
    }

    func drawDots(withFill: Bool, loopNumber: Int) {
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: 30, height: 30))
        let img = renderer.image {
            ctx in

            if withFill {
                ctx.cgContext.setFillColor(UIColor.white.cgColor)
            }

            ctx.cgContext.setStrokeColor(UIColor.white.cgColor)

            ctx.cgContext.setLineWidth(2)
            let rectangle = CGRect(x: 2.5, y: 2.5, width: 25, height: 25)
            ctx.cgContext.addEllipse(in: rectangle)

            if withFill {
                ctx.cgContext.drawPath(using: .fillStroke)
            } else {
                ctx.cgContext.drawPath(using: .stroke)
            }

        }
        let image = UIImageView(image: img)
        image.center = CGPoint(x: deviceAnchor6 + deviceAnchor6 * loopNumber, y: Int(self.view.bounds.height * 0.41))
        image.my_dropShadow()

        weekdayDots.addSubview(image)
    }
    
    func configureBar() {
        
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: Int(CGFloat(270).barRelativeToWidth), height: Int(CGFloat(30).barRelativeToWidth)))
        let img = renderer.image {
            ctx in
            ctx.cgContext.setStrokeColor(UIColor.white.cgColor)
            ctx.cgContext.setLineWidth(2)
            let rectangle = CGRect(x: 2, y: 5, width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth))
            let roundedNumber = Int(CGFloat(20).barRelativeToWidth) / 2
            let rounded = CGPath.init(roundedRect: rectangle, cornerWidth: CGFloat(roundedNumber), cornerHeight: CGFloat(roundedNumber), transform: nil)
            ctx.cgContext.addPath(rounded)
                ctx.cgContext.drawPath(using: .stroke)
        }
        
        let image = UIImageView(image: img)
     
        image.center = CGPoint(x: Int(self.view.bounds.midX), y: Int(self.view.bounds.midY) + Int(CGFloat(20).barRelativeToWidth))
        image.my_dropShadow()
        barImage.addSubview(image)
        view.addSubview(barImage)
        view.bringSubviewToFront(barImage)
        
    }
    
    
   func configureProgressBar() {
        let midPointX = Int(self.view.bounds.midX)
        let midPointY = Int(self.view.bounds.midY)
       let barStartingPoint = Int(midPointX - Int(CGFloat(123).barRelativeToWidth))
        let progressBarY = midPointY + Int(CGFloat(20).barRelativeToWidth)
    
        progressBar.clipsToBounds = true
        progressBar.layer.cornerRadius = CGFloat(10).barRelativeToWidth
        progressBar.alpha = 0
    
            if Date().isSchoolDay() {
                switch timeOfDay! {
                case .before:
                    progressBar.center = CGPoint(x: barStartingPoint, y: progressBarY)
                     progressBar.bounds.size = CGSize(width: Int(CGFloat(20).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth))
                    progressBar.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth))))
                    view.addSubview(progressBar)
                case .during:
                    loadProgressingBar(isInitial: true)
                case .after:
                    progressBar.center = CGPoint(x: midPointX, y: progressBarY)
                    progressBar.bounds.size = CGSize(width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth))
                    progressBar.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth))))
                    view.addSubview(progressBar)
                    
                }
            } 
    }
    
    func loadProgressingBar(isInitial: Bool) {
        var numerator = CGFloat()
         let denominator = CGFloat(numOfMinAtSchool(type: today)!)
        var percentage = CGFloat()
        let midPointX = Int(self.view.bounds.midX)
        let midPointY = Int(self.view.bounds.midY)
        let barStartingPoint = Int(midPointX - Int(CGFloat(123).barRelativeToWidth))
        let bound = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: CGFloat(266).barRelativeToWidth, height: CGFloat(20).barRelativeToWidth))
         progressBar.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: bound)
        if isInitial {
            numerator = CGFloat(Date().localTime().minFromSchoolStart())
          
             percentage = numerator / denominator
           
            progressBar.center = CGPoint(x: (barStartingPoint) + Int(CGFloat(123).barRelativeToWidth * percentage), y: midPointY + Int(CGFloat(20).barRelativeToWidth))
            progressBar.bounds.size = CGSize(width: CGFloat(20) + (CGFloat(246).barRelativeToWidth * percentage), height: CGFloat(20).barRelativeToWidth)
            view.addSubview(progressBar)

            view.bringSubviewToFront(barImage)

        } else {
            numerator = CGFloat(Date().localTime().minFromSchoolStart())
            percentage = numerator / denominator
            UIView.animate(withDuration: 1.5) {
                self.progressBar.center = CGPoint(x: (barStartingPoint) + Int(CGFloat(123).barRelativeToWidth * percentage), y: midPointY + Int(CGFloat(20).barRelativeToWidth))
                self.progressBar.bounds.size = CGSize(width: CGFloat(20).barRelativeToWidth + (CGFloat(246).barRelativeToWidth * percentage), height: CGFloat(20).barRelativeToWidth)
            }
        }
      
    }
    
    func configureBarLabel(type: Int) {
        var classLabels = my_getPeriodsFromToday(type: type)
        let startingPosition = (deviceMax - Int(CGFloat(250).barRelativeToWidth)) / 2
        let endingPosition = startingPosition +  Int(CGFloat(250).barRelativeToWidth)
        var distance = Int()
        if classLabels.count > 1 {
             distance = (endingPosition - startingPosition) / ( classLabels.count - 1 )
            for i in 0...( classLabels.count - 1 ) {
                let classLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 20))
                classLabel.center = CGPoint(x: startingPosition + distance * i, y: Int(self.view.bounds.midY) + Int(CGFloat(50).barRelativeToWidth))
                classLabel.textAlignment = .center
                classLabel.text = classLabels[i]
                classLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(19).relativeToWidth)
                classLabel.textColor = UIColor.white
                classLabel.my_dropShadow()
                todayClassLabel.addSubview(classLabel)
                view.addSubview(todayClassLabel)
            }
        } else {
             distance = endingPosition - startingPosition
            let classLabel = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat(distance), height: 30))
            classLabel.center = CGPoint(x: (startingPosition + endingPosition) / 2, y: Int(self.view.bounds.midY) + Int(CGFloat(50).barRelativeToWidth))
            classLabel.textAlignment = .center
            classLabel.text = classLabels[0]
            
            classLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(19).relativeToWidth)
            classLabel.textColor = UIColor.white
            classLabel.my_dropShadow()
            
            todayClassLabel.addSubview(classLabel)
            view.addSubview(todayClassLabel)
          
        }
    }
    
    
    @objc func fetchEvents() {
     self.configureEvents()
//        if CheckInternet.Connection() {
//            var date = Date()
//            var time = String()
//            var eventTitle = String()
//            var notification = Bool()
//            if let data = try? String(contentsOf: URL(string: "https://portola.epicteam.app/api/events")!) {
//                let jsonData = JSON(parseJSON: data).dictionaryValue["events"]!
//
//                let array = jsonData.arrayValue
//                for events in array {
//                    let dictionary = events.dictionaryObject!
//                    if let dateGet = dictionary["date"] as? String {
//
//
//                            let formatter = DateFormatter()
//                            formatter.timeZone = Calendar.current.timeZone
//                            formatter.locale = Calendar.current.locale
//                            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
//                            let UTCDate = formatter.date(from: dateGet) ?? Date.distantPast
//                            let currentDate = Calendar.current.date(byAdding: .hour, value: -UTCDifference(), to: UTCDate) ?? Date.distantPast
//                            date = currentDate
//
//                    } else {
//                        date = Date.distantPast
//                    }
//                    if let timeGet = dictionary["time"] as? String {
//                        time = timeGet
//                    } else {
//                        time = "N/A"
//                    }
//                    if let eventTitleGet = dictionary["title"] as? String {
//                        eventTitle = eventTitleGet
//                    } else {
//                        eventTitle = "N/A"
//                    }
//                    if let notificationGet = dictionary["notify"] as? Bool {
//                        notification = notificationGet
//                    }
//
//                    let currentEvent = SchoolEvents()
//                    currentEvent.date = date
//                    currentEvent.time = time
//                    currentEvent.title = eventTitle
//                    currentEvent.notification = notification
//                    schoolEvents.append(currentEvent)
//
//                }
//            }
//        } else {
//            let ac = UIAlertController(title: "No Internet Connection", message: "Could not load any upcoming events because there is no Internet connection.", preferredStyle: .alert)
//            ac.addAction(UIAlertAction(title: "OK", style: .cancel))
//            present(ac, animated: true)
//        }
//
//        DispatchQueue.main.async {
//            self.configureEvents()
//        }
    }

    func configureEvents() {
//        if schoolEvents.count > 0 {
//            schoolEvents = schoolEvents.filter {
//                $0.date.noon >= Date().noon
//
//            }
//            schoolEvents = schoolEvents.sorted(by: {$0.date < $1.date})
//            for events in schoolEvents {
//                if let dayAway = my_daysAwayFromToday(date: events.date.noon) {
//                    if dayAway == 0 {
//                        eventTimes.append("TODAY, \(events.time.uppercased())")
//                    } else if dayAway == 1 {
//                        eventTimes.append("TOMORROW, \(events.time.uppercased())")
//                    } else if dayAway < 7 {
//                        let weekday = getWeekdayString(date: events.date, isUpper: true)
//                        eventTimes.append("\(weekday), \(events.time.uppercased())")
//                    } else {
//                        let day = Calendar.current.component(.day, from: events.date)
//                        let month = Calendar.current.component(.month, from: events.date)
//                        let dateString = "\(month)/\(day)"
//                        eventTimes.append("\(dateString), \(events.time.uppercased())")
//                    }
//                }
//                    eventTitles.append(events.title)
//            }
//
//
//            switch schoolEvents.count {
//            case 1:
//                self.eventTime1.text = eventTimes[0]
//
//                self.eventTitle1.text = eventTitles[0]
//
//            case 2:
//                self.eventTime1.text = eventTimes[0]
//                self.eventTime2.text = eventTimes[1]
//                self.eventTitle1.text = eventTitles[0]
//                self.eventTitle2.text = eventTitles[1]
//
//            default:
//                self.eventTime1.text = eventTimes[0]
//                self.eventTime2.text = eventTimes[1]
//                self.eventTime3.text = eventTimes[2]
//                self.eventTitle1.text = eventTitles[0]
//                self.eventTitle2.text = eventTitles[1]
//                self.eventTitle3.text = eventTitles[2]
//            }
//
//
//
//        } else {
//
//
//        }
        
        
        self.eventTime2.text = "INTEGRAL, AVAILABLE NOW"
        eventTime2.font = UIFont(name: "Lato-Light", size: CGFloat(24).relativeToWidth)
    
    }

    
    
    
    
    @objc func configureNextSchoolDayStart() {
       
            DispatchQueue.main.async {
                self.loadEndsLabel(text: "SCHOOL STARTS")
            }
            let startingDate = Date().noon
            var interval = 1
            var dayType = 20
            while dayType == 20 {
                let onDate = Calendar.current.date(byAdding: .day, value: interval, to: startingDate)!
                if onDate.isWeekend() {
                    dayType = 20
                } else {
                    dayType = getDayType(date: onDate)
                }
                
                interval += 1
                
                if dayType != 20 {
                    
                    //found a non-20 day
                    let currentDate = onDate.noon
                    let firstDayStartTime = uniq(source: my_getSchedule(type: dayType, date: currentDate)!).first!
                    
                    let time = timeStringFromDate(date: firstDayStartTime)
                    DispatchQueue.main.async {
                        self.loadTimeLeftLabel(text: time, size: CGFloat(140))
                    }
                    
                    if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day == 1 {
                        DispatchQueue.main.async {
                            self.loadMinutesLabel(text: "TOMORROW")
                        }
                    } else if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day! < 7  {
                        DispatchQueue.main.async {
                            self.loadMinutesLabel(text: getWeekdayString(date: currentDate, isUpper: true))
                        }
                    } else {
                        let formatter = DateFormatter()
                        formatter.dateFormat = "M/d"
                        let schoolStartsString = formatter.string(from: currentDate)
                        DispatchQueue.main.async {
                            self.loadMinutesLabel(text: "ON \(schoolStartsString)")
                        }
                    }
                }
            }
        
        
    }
    
    func loadTimeLeftLabel(text: String, size: CGFloat) {
        DispatchQueue.main.async {
            self.timeLeftLabel.text = text
            self.timeLeftLabel.font = UIFont(name: "Heebo-Light", size: size.relativeToWidth)
            self.timeLeftLabel.fadeIn()
        }
        
    }
    
    func loadEndsLabel(text: String) {
        DispatchQueue.main.async {
            self.endsLabel.text = text
            self.endsLabel.fadeIn()
        }
       
    }
    
    func loadMinutesLabel(text: String) {
        DispatchQueue.main.async {
            self.minutesLabel.text = text
            self.minutesLabel.fadeIn()
        }
    }
    
   @objc func configureTimeLeftLabel() {
    if Date() > lastDay && Date() < firstDay2019 || (Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .after) {
        
        loadEndsLabel(text: "SCHOOL STARTS IN")
        loadMinutesLabel(text: "DAYS")
        dateDifference = Calendar.current.dateComponents([.day], from: Date(), to: firstDay2019).day ?? 0
        loadTimeLeftLabel(text: String(dateDifference), size: CGFloat(140))
        
    } else {
       // print(Calendar.current.component(.day, from: Date()))
        print(Calendar.current.component(.day, from: lastDay))
        if Date().isSchoolDay() {
            switch timeOfDay! {
                
            case .before:
                let startTime = uniq(source: my_getSchedule(type: today, date: nil)!).first!
                loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140))
                loadEndsLabel(text: "SCHOOL STARTS")
                loadMinutesLabel(text: "TODAY")
            case .during:
                
                fetchTimeLeft()
            case .after:
                if tomorrow == 20 {
                    
                    performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                } else {
                    if Calendar.current.component(.weekday, from: Date()) == 6 {
                        if nextMonday == 20 {
                            
                            performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                        } else {
                            let startTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first!
                            loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140))
                            loadEndsLabel(text: "SCHOOL STARTS")
                            loadMinutesLabel(text: "MONDAY")
                        }
                        
                    } else {
                        let startTime = uniq(source: my_getSchedule(type: tomorrow, date: Date().tomorrow)!).first!
                        
                        loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140))
                        loadEndsLabel(text: "SCHOOL STARTS")
                        loadMinutesLabel(text: "TOMORROW")
                    }
                }
                
                
            }
            
            
        } else {
            if Date().isWeekend() {
                if nextMonday == 20 {
                    
                    performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                } else {
                    
                    let mondayStartTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first!
                    
                    loadTimeLeftLabel(text: timeStringFromDate(date: mondayStartTime), size: 140)
                    loadEndsLabel(text: "SCHOOL STARTS")
                    
                    switch Calendar.current.component(.weekday, from: Date()) {
                    case 7:
                        loadMinutesLabel(text: "MONDAY")
                    case 1:
                        loadMinutesLabel(text: "TOMORROW")
                    default:
                        loadMinutesLabel(text: "MONDAY")
                    }
                }
            } else {
                
                performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                
            }
        }
    }
    
        
       
    }

    
    @objc func fetchTimeLeft() {
        var label = String()
        var end = String()
        if let newSchedule = my_getSchedule(type: today, date: nil) {
            let schedule = uniq(source: newSchedule)
            for i in 0...schedule.count - 1 {
              
                if schedule[i] >= Date().localTime() {
                    
                    if Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .during {
                        if let seconds = Calendar.current.dateComponents([.second], from: Date().localTime(), to: schedule.last!).second {
                            if seconds >= 10000 {
                                loadTimeLeftLabel(text: String(seconds), size: 90)
                                loadMinutesLabel(text: "SECONDS")
                            } else if seconds >= 1000 {
                                loadTimeLeftLabel(text: String(seconds), size: 120)
                                loadMinutesLabel(text: "SECONDS")
                            } else {
                                loadTimeLeftLabel(text: String(seconds), size: 160)
                                loadMinutesLabel(text: "SECONDS")
                            }
                            loadEndsLabel(text: "SCHOOL YEAR ENDS IN")
                        }
                    } else {
                        if let minutes = Calendar.current.dateComponents([.minute], from: Date().localTime(), to: schedule[i]).minute {
                            if minutes == 0 {
                                loadTimeLeftLabel(text: "<1", size: 160)
                                loadMinutesLabel(text: "MINUTE")
                            } else if minutes == 1 {
                                loadTimeLeftLabel(text: String(minutes), size: 160)
                                loadMinutesLabel(text: "MINUTE")
                            } else {
                                loadTimeLeftLabel(text: String(minutes), size: 160)
                                loadMinutesLabel(text: "MINUTES")
                            }
                            
                            if let rawLabel = my_getStartEndPeriodLabel(type: today) {
                                let rawLabelNumber = rawLabel[i - 1]
                                label = rawLabelNumber.getPeriodLabel()
                                if let startEndLabel = my_getStartEndLabel(type: today) {
                                    let isStart = startEndLabel[i - 1]
                                    end = isStart.startEndLabelFromBool()
                                    loadEndsLabel(text: "\(label) \(end) IN")
                                    
                                    break
                                }
                            }
                        }
                    }
                    
                 

                }
               
            }
        }
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  AthleticsViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/17/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import Segmentio

class AthleticsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    @IBAction func dismiss(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var segmentioView: Segmentio!
    var content = [SegmentioItem]()
    let allIcons = ["Baseball", "Boys Basketball", "Track", "Football", "Girls Golf", "Girls Lacrosse", "Boys Soccer", "Softball", "Girls Tennis", "Swim", "Cross Country", "Girls Volleyball", "Boys Water Polo","Wrestling", "Girls Basketball", "Boys Golf", "Boys Lacrosse", "Girls Soccer", "Boys Tennis", "Girls Water Polo", "Boys Volleyball"]
    let allImages: [UIImage] = [
        UIImage(named: "Baseball")!,
        UIImage(named: "Basketball")!,
        UIImage(named: "Track")!,
        UIImage(named: "Football")!,
        UIImage(named: "Golf")!,
        UIImage(named: "Lacrosse")!,
        UIImage(named: "Soccer")!,
        UIImage(named: "Softball")!,
         UIImage(named: "Tennis")!,
        UIImage(named: "Swim")!,
        UIImage(named: "CrossCountry")!,
        UIImage(named: "Volleyball")!,
        UIImage(named: "Water Polo")!,
        UIImage(named: "Wrestling")!,
        UIImage(named: "Basketball")!,
        UIImage(named: "Golf")!,
        UIImage(named: "Lacrosse")!,
        UIImage(named: "Soccer")!,
         UIImage(named: "Tennis")!,
        UIImage(named: "Water Polo")!,
        UIImage(named: "Volleyball")!
    ]
    
    let fallIndex: [Int] = [3, 4, 8, 10, 11, 12]
    let winterIndex: [Int] = [1, 6, 17, 14, 13, 19]
    let springIndex: [Int] = [0, 2, 5, 7, 9, 15, 16, 18, 20]
    
    var fallIcons = [String]()
    var winterIcons = [String]()
    var springIcons = [String]()
    var fallImages = [UIImage]()
    var winterImages = [UIImage]()
    var springImages = [UIImage]()
    
    var onDisplay = [String]()
    var displayedImages = [UIImage]()
    
    var sportToPass = String()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
        setSegmentedControl()
        collectionView.delegate = self
        collectionView.dataSource = self
        
        segmentioView.selectedSegmentioIndex = 0
        onDisplay = allIcons
        displayedImages = allImages
        
        for index in fallIndex {
            fallIcons.append(allIcons[index])
            fallImages.append(allImages[index])
        }
        
        for index in winterIndex {
            winterIcons.append(allIcons[index])
            winterImages.append(allImages[index])
        }
        for index in springIndex {
            springIcons.append(allIcons[index])
            springImages.append(allImages[index])
        }
        
        let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 5
        layout.itemSize = CGSize(width: self.view.bounds.width / 2, height: self.view.bounds.width / 2)
        collectionView.allowsMultipleSelection = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        for cell in collectionView.indexPathsForSelectedItems ?? [] {
            collectionView.deselectItem(at: cell, animated: true)
            let deselectedCell = collectionView.cellForItem(at: cell)
            deselectedCell?.backgroundColor = UIColor.white
        }
        
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        
        segmentioView.valueDidChange = { segmentio, segmentIndex in
            switch segmentIndex {
            case 0:
                self.onDisplay = self.allIcons
                self.displayedImages = self.allImages
            case 1:
                self.onDisplay = self.fallIcons
                self.displayedImages = self.fallImages
            case 2:
                self.onDisplay = self.winterIcons
                self.displayedImages = self.winterImages
            case 3:
                self.onDisplay = self.springIcons
                self.displayedImages = self.springImages
            default:
                self.onDisplay = self.allIcons
                self.displayedImages = self.allImages
            }
            self.collectionView.reloadData()
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func setSegmentedControl() {
      
        view.addSubview(segmentioView)
        let position = SegmentioPosition.dynamic
        let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white)
        let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none)
        let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0))
        segmentioView.selectedSegmentioIndex = 0
        let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: (
            defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)),
            selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white),
            highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white)
            )
            ,animationDuration: 0.2)
        let allItem = SegmentioItem(title: "ALL", image: nil)
        let fallItem = SegmentioItem(title: "FALL", image: nil)
        let winterItem = SegmentioItem(title: "WINTER", image: nil)
        let springItem = SegmentioItem(title: "SPRING", image: nil)
        content = [allItem, fallItem, winterItem, springItem]
        segmentioView.setup(content: content, style: .onlyLabel, options: options)
        
    }
    
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sports", for: indexPath) as! AthleticsCollectionViewCell
        cell.iconImage.image = displayedImages[indexPath.item]
        cell.iconLabel.text = onDisplay[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.width / 2)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return onDisplay.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
        let item = cell as! AthleticsCollectionViewCell
        sportToPass = item.iconLabel.text!
        performSegue(withIdentifier: "athleticDetail", sender: nil)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.backgroundColor = UIColor.white
    }
    
    
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "athleticDetail" {
            let vc = segue.destination as! AthleticsDetailViewController
            vc.sport = sportToPass
            
        }
    }
 

}
<file_sep>//
//  TodayViewController.swift
//  PHSWidget
//
//  Created by <NAME> on 10/16/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import NotificationCenter

enum dayType {
    case today
    case tomorrow
    case nextMonday
    case custom
}
func getDayType(date: Date) -> Int {
    
    var isSpecial = false
    for days in specialDays {
        if days.date.noon == date.noon {
            isSpecial = true
            return Int(days.type)
        }
    }
    if isSpecial == false {
        return 0
    }
    
}
var today = Int()
var tomorrow = Int()
var nextMonday = Int()
    var specialDays = [SpecialDays]()
class TodayViewController: UIViewController, NCWidgetProviding {
    @IBOutlet weak var endsLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var minutesLabel: UILabel!
   

    var day = Calendar.current.component(.day, from: Date())
    var minute = Calendar.current.component(.minute, from: Date())
    var timeOfDay: relativeTime?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.timeOfDay = Date().timeOfSchoolDay()
        loadSpecialDays()
           getTodayType()
        configureTimeLeftLabel()
         Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
        if Date().isSchoolDay() {
            if Date().timeOfSchoolDay() == relativeTime.during {
                fetchTimeLeft()
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
       
    }
    func loadSpecialDays() {
        if let data = Bundle.main.path(forResource: "specialDays", ofType: "txt") {
       
            if let content = try? String(contentsOfFile: data) {
                
                if let jsonData = JSON(parseJSON: content).dictionaryValue["specialDays"]?.arrayValue {
                    
                    for days in jsonData {
                        
                        let detail = days.dictionaryObject!
                        let object = SpecialDays()
                        if let date = detail["date"] as? String {
                            let formatter = DateFormatter()
                            formatter.dateFormat = "yyyy/M/dd"
                            formatter.timeZone = Calendar.current.timeZone
                            formatter.locale = Calendar.current.locale
                            object.date = formatter.date(from: date)!
                        }
                        if let type = detail["case"] as? Int {
                            object.type = type
                        }
                        specialDays.append(object)
                    }
                }
                
            }
        } else {
            print("no")
        }
        
    }
   

    func getTodayType() {
        today = 0
        tomorrow = 0
        nextMonday = 0
        for days in specialDays {
            
            if Date().noon == days.date.noon {
                today = days.type
                
            }
            if Date().tomorrow == days.date.noon {
                tomorrow = days.type
                
            }
            if Date().nextMonday().noon == days.date.noon {
                nextMonday = days.type
                
            }
        }
        
    }
    

    @objc func update() {
        if Calendar.current.component(.day, from: Date()) != day {
            getTodayType()
            timeOfDay = Date().timeOfSchoolDay()
            configureTimeLeftLabel()
          
            day = Calendar.current.component(.day, from: Date())
        } else {
            if timeOfDay != Date().timeOfSchoolDay() {
                timeOfDay = Date().timeOfSchoolDay()
                self.configureTimeLeftLabel()
               
            } else {
                if minute != Calendar.current.component(.minute, from: Date()) {
                    
                    if Date().isSchoolDay() {
                        if timeOfDay == .during {
                            fetchTimeLeft()
                           
                        }
                    }
                    minute = Calendar.current.component(.minute, from: Date())
                }
            }
            
        }
        
        
    }
  
    @objc func configureTimeLeftLabel() {
        if Date().isSchoolDay() {
            
            switch timeOfDay! {
                
            case .before:
                let startTime = uniq(source: my_getSchedule(type: today, date: nil)!).first!
                loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140))
                loadEndsLabel(text: "SCHOOL STARTS")
                loadMinutesLabel(text: "TODAY")
            case .during:
                
                fetchTimeLeft()
            case .after:
                if tomorrow == 20 {
                    
                    performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                } else {
                    if Calendar.current.component(.weekday, from: Date()) == 6 {
                        if nextMonday == 20 {
                            
                            performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                        } else {
                            let startTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first!
                            loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140))
                            loadEndsLabel(text: "SCHOOL STARTS")
                            loadMinutesLabel(text: "MONDAY")
                        }
                        
                    } else {
                        let startTime = uniq(source: my_getSchedule(type: tomorrow, date: Date().tomorrow)!).first!
                        
                        loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140))
                        loadEndsLabel(text: "SCHOOL STARTS")
                        loadMinutesLabel(text: "TOMORROW")
                    }
                }
                
                
            }
            
            
        } else {
            if Date().isWeekend() {
                if nextMonday == 20 {
                    
                    performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                } else {
                    
                    let mondayStartTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first!
                    
                    loadTimeLeftLabel(text: timeStringFromDate(date: mondayStartTime), size: 140)
                    loadEndsLabel(text: "SCHOOL STARTS")
                    
                    switch Calendar.current.component(.weekday, from: Date()) {
                    case 7:
                        loadMinutesLabel(text: "MONDAY")
                    case 1:
                        loadMinutesLabel(text: "TOMORROW")
                    default:
                        loadMinutesLabel(text: "MONDAY")
                    }
                }
            } else {
                
                performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil)
                
            }
        }
        
        
    }
    
    
    @objc func fetchTimeLeft() {
        var label = String()
        var end = String()
        if let newSchedule = my_getSchedule(type: today, date: nil) {
            let schedule = uniq(source: newSchedule)
            for i in 0...schedule.count - 1 {
                
                if schedule[i] >= Date().localTime() {
                    if let minutes = Calendar.current.dateComponents([.minute], from: Date().localTime(), to: schedule[i]).minute {
                        if minutes == 0 {
                            loadTimeLeftLabel(text: "<1", size: 160)
                            loadMinutesLabel(text: "MINUTE")
                        } else if minutes == 1 {
                            loadTimeLeftLabel(text: String(minutes), size: 160)
                            loadMinutesLabel(text: "MINUTE")
                        } else {
                            loadTimeLeftLabel(text: String(minutes), size: 160)
                            loadMinutesLabel(text: "MINUTES")
                        }
                        
                        if let rawLabel = my_getStartEndPeriodLabel(type: today) {
                            let rawLabelNumber = rawLabel[i - 1]
                            label = rawLabelNumber.getPeriodLabel()
                            if let startEndLabel = my_getStartEndLabel(type: today) {
                                let isStart = startEndLabel[i - 1]
                                end = isStart.startEndLabelFromBool()
                                loadEndsLabel(text: "\(label) \(end) IN")
                                
                                break
                            }
                        }
                    }
                    
                }
                
            }
        }
    }
    
    @objc func configureNextSchoolDayStart() {
        DispatchQueue.main.async {
            self.loadEndsLabel(text: "SCHOOL STARTS")
        }
        let startingDate = Date().noon
        var interval = 1
        var dayType = 20
        while dayType == 20 {
            let onDate = Calendar.current.date(byAdding: .day, value: interval, to: startingDate)!
            if onDate.isWeekend() {
                dayType = 20
            } else {
                dayType = getDayType(date: onDate)
            }
            
            interval += 1
            
            if dayType != 20 {
                
                //found a non-20 day
                let currentDate = onDate.noon
                let firstDayStartTime = uniq(source: my_getSchedule(type: dayType, date: currentDate)!).first!
                
                let time = timeStringFromDate(date: firstDayStartTime)
                DispatchQueue.main.async {
                    self.loadTimeLeftLabel(text: time, size: CGFloat(140))
                }
                
                if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day == 1 {
                    DispatchQueue.main.async {
                        self.loadMinutesLabel(text: "TOMORROW")
                    }
                } else if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day! < 7  {
                    DispatchQueue.main.async {
                        self.loadMinutesLabel(text: getWeekdayString(date: currentDate, isUpper: true))
                    }
                } else {
                    let formatter = DateFormatter()
                    formatter.dateFormat = "M/d"
                    let schoolStartsString = formatter.string(from: currentDate)
                    DispatchQueue.main.async {
                        self.loadMinutesLabel(text: "ON \(schoolStartsString)")
                    }
                }
            }
        }
    }
    
    func loadTimeLeftLabel(text: String, size: CGFloat) {
        DispatchQueue.main.async {
            self.timeLabel.text = text
       
        }
        
    }
    
    func loadEndsLabel(text: String) {
        DispatchQueue.main.async {
            self.endsLabel.text = text
       
        }
        
    }
    
    func loadMinutesLabel(text: String) {
        DispatchQueue.main.async {
            self.minutesLabel.text = text
          
        }
    }
    func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
        
        // Perform any setup necessary in order to update the view.
        
        // If an error is encountered, use NCUpdateResult.Failed
        // If there's no update required, use NCUpdateResult.NoData
        // If there's an update, use NCUpdateResult.NewData
         completionHandler(NCUpdateResult.newData)
       
    }
    
}
<file_sep>//
//  my_UTC.swift
//  PHS App
//
//  Created by <NAME> on 8/6/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
extension Date {
    func UTC() -> Date {
        if let date = Calendar.current.date(byAdding: .hour, value: UTCDifference(), to: self) {
            return date
        } else {
            return Date()
        }
      
    }
}
<file_sep>//
//  my_dropShadow.swift
//  PHS App
//
//  Created by <NAME> on 7/22/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit





extension UIView {
    func my_dropShadow() {
        let size = layer.frame.size.height
        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.gray.cgColor
        self.layer.shadowOffset = CGSize(width: size * 0.04, height: size * 0.04)
        self.layer.shadowRadius = size * 0.05
        self.layer.shadowOpacity = 0.8
    }
    
  
}
<file_sep>//
//  DayType+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/10/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension DayType {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<DayType> {
        return NSFetchRequest<DayType>(entityName: "DayType")
    }

    @NSManaged public var type: Int16
    @NSManaged public var date: Date

}
<file_sep>//
//  Houses.swift
//  PHS App
//
//  Created by <NAME> on 10/3/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class Houses: NSObject {
    var points = Int()
    var name = String() 
}
<file_sep>//
//  my_daysAwayFromToday.swift
//  PHS App
//
//  Created by <NAME> on 7/29/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

 func my_daysAwayFromToday(date: Date) -> Int? {
    let today = Date().noon
    let dateGet = date.noon
    if let interval = Calendar.current.dateComponents([.day], from: today, to: dateGet).day {
        return interval
    } else {
        return nil
    }
}
<file_sep>//
//  my_setNavigationBar.swift
//  PHS App
//
//  Created by <NAME> on 7/25/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit

extension UINavigationBar {
    func my_setNavigationBar() {
        
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        
    }
    
    static func createNavigationBar() -> UINavigationBar {
        let navigationBar = UINavigationBar()
        navigationBar.my_setNavigationBar()
        return navigationBar
    }
    
}
<file_sep>//
//  HomeScrollViewController.swift
//  PHS App
//
//  Created by <NAME> on 9/20/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class HomeScrollViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, UIScrollViewDelegate {
    
    var pageContainer = UIPageViewController(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation(rawValue: 0)!, options: nil)

    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var distanceConstant: NSLayoutConstraint!
    
    fileprivate lazy var pages: [UIViewController] = {
        return [
            storyboard!.instantiateViewController(withIdentifier: "home"),
            storyboard!.instantiateViewController(withIdentifier: "bellSchedule")

        ]
    }()
    
    var currentPage = 0
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
//        if self.distanceConstant.constant >= self.distanceConstant.constant.barRelativeToWidth {
//            self.distanceConstant.constant = self.distanceConstant.constant.relativeToWidth
//        } else {
//            self.distanceConstant.constant = self.distanceConstant.constant + CGFloat(20)
//        }
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        pageContainer.delegate = self
        pageContainer.dataSource = self
        
        if let firstVC = pages.first {
           
            pageContainer.setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
            
        }
        
        view.addSubview(pageContainer.view)
        view.bringSubviewToFront(pageControl)
      
        for subview in pageContainer.view.subviews {
            if let scrollView = subview as? UIScrollView {
                scrollView.delegate = self
                break
            }
        }
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if (currentPage == 0 && scrollView.contentOffset.x < scrollView.bounds.size.width) {
            scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0);
        } else if (currentPage == pages.count - 1 && scrollView.contentOffset.x > scrollView.bounds.size.width) {
            scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0);
        }
    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        if (currentPage == 0 && scrollView.contentOffset.x <= scrollView.bounds.size.width) {
            targetContentOffset.pointee = CGPoint(x: scrollView.bounds.size.width, y: 0);
        } else if (currentPage == pages.count - 1 && scrollView.contentOffset.x >= scrollView.bounds.size.width) {
            targetContentOffset.pointee = CGPoint(x: scrollView.bounds.size.width, y: 0);
        }
    }
    
//    func presentationCount(for pageViewController: UIPageViewController) -> Int {
//        return pages.count
//    }
//
//    func presentationIndex(for pageViewController: UIPageViewController) -> Int {
//        return currentPage
//    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if (!completed)
        {
            return
        }
        if let currentViewController = pageContainer.viewControllers!.first {
            if let currentIndex = pages.index(of: currentViewController) {
              currentPage = currentIndex
            }
        }
        pageControl.currentPage = currentPage
    }

 
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
     
        guard let viewControllerIndex = pages.index(of: viewController) else {return nil }
       
        let previousIndex = viewControllerIndex - 1
        
        guard previousIndex >= 0
            else {return nil }
        
        guard pages.count > previousIndex
            else {return nil}
        
        return pages[previousIndex]
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
       
        guard let viewControllerIndex = pages.index(of: viewController) else { return nil }
        

        let nextIndex = viewControllerIndex + 1
        guard nextIndex < pages.count else { return nil }
        guard pages.count > nextIndex else { return nil}
        return pages[nextIndex]
    }
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  my_removeDuplicates.swift
//  PHS App
//
//  Created by <NAME> on 9/12/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit

func uniq<S: Sequence, T: Hashable>(source: S) -> [T] where S.Iterator.Element == T {
    var buffer = [T]()
    var added = Set<T>()
    for elem in source {
        if !added.contains(elem) {
            buffer.append(elem)
            added.insert(elem)
        }
    }
    return buffer
}

<file_sep>//
//  my_minutesFromSchoolStart.swift
//  PHS App
//
//  Created by <NAME> on 8/4/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

extension Date {
    func minFromSchoolStart() -> Int {
        if today == 20 || !self.isSchoolDay() {
            return 1
        } else {
            let now = self
            
            let todaySchedule = my_getSchedule(type: today, date: self)
            let start = todaySchedule!.first!
            let interval = Calendar.current.dateComponents([.minute], from: start, to: now).minute
            return interval!
        }
        
        
    }
}
<file_sep>//
//  CalendarViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/13/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import JTAppleCalendar

class CalendarViewController: UIViewController, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
  
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var calendarView: JTAppleCalendarView!
    @IBOutlet weak var monthLabel: UILabel!
    @IBOutlet weak var calendarHolder: UIView!
    @IBOutlet weak var leftArrow: UIImageView!
    @IBOutlet weak var rightArrow: UIImageView!
    @IBOutlet weak var  noSchoolLabel: UILabel!
    @IBAction func dismiss(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBOutlet weak var backgroundView: UIView!
    @IBOutlet weak var dateDetail: UIView!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var weekdayLabel: UILabel!
    @IBOutlet weak var periodLabel: UILabel!
    @IBOutlet weak var startEndLabel: UILabel!
    
    
     let formatter = DateFormatter()
    var specialDates = [Date]()
    var dateRange = [Date]()
    func initializeCalendar() {
        calendarHolder.layer.shadowColor = UIColor.gray.cgColor
        calendarHolder.layer.shadowRadius = 4
        calendarHolder.layer.shadowOpacity = 0.35
        calendarHolder.layer.shadowOffset = CGSize(width: 5, height: 5)
        
        calendarView.calendarDelegate = self
        calendarView.calendarDataSource = self
        calendarView.minimumInteritemSpacing = 0
        calendarView.minimumLineSpacing = 0
        calendarView.allowsMultipleSelection = false
        calendarView.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
       
        
        
        calendarView.visibleDates { (visibleDates) in
            let date = visibleDates.monthDates.first!.date
            self.formatter.dateFormat = "MMMM"
            self.monthLabel.text = self.formatter.string(from: date).uppercased()
        }
       
        
        
        dateDetail.layer.shadowColor = UIColor.gray.cgColor
        dateDetail.layer.shadowRadius = 4
        dateDetail.layer.shadowOpacity = 0.35
        dateDetail.layer.shadowOffset = CGSize(width: 5, height: 5)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
        backgroundView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.15)
        initializeCalendar()
        
        for objects in specialDays {
            
            specialDates.append(objects.date.noon)
        }
        let leftGesture = UITapGestureRecognizer(target: self, action: #selector(leftTapped))
        leftGesture.delegate = self
        leftArrow.addGestureRecognizer(leftGesture)
        let rightGesture = UITapGestureRecognizer(target: self, action: #selector(rightTapped))
        rightGesture.delegate = self
        rightArrow.addGestureRecognizer(rightGesture)
        formatter.dateFormat = "yyyy MM dd"
        formatter.timeZone = Calendar.current.timeZone
        formatter.locale = Calendar.current.locale
        let startDate = formatter.date(from: "2019 08 01")!
        let endDate = formatter.date(from: "2020 08 31")!
        dateRange = calendarView.generateDateRange(from: startDate, to: endDate)
        configureDayDetail(withDate: Date().noon)
        calendarView.scrollToDate(Date(), animateScroll: false)

      
    }
   
    
    
    
    func configureDayDetail(withDate date: Date) {
        periodLabel.isHidden = false
        startEndLabel.isHidden = false
        noSchoolLabel.isHidden = true
        var dayType = getDayType(date: date)
        if dayType == 0 {
            dayType = Calendar.current.component(.weekday, from: date) + 20
        }
        dateLabel.text = "\(Calendar.current.component(.month, from: date))/\(Calendar.current.component(.day, from: date))"
        weekdayLabel.text = getWeekdayString(date: date, isUpper: true)
        if date.isSchoolDay() {
            let periods = my_getPeriodsFromToday(type: dayType)
            periodLabel.text = periods.joined(separator: ", ")
            let schedule = my_getSchedule(type: dayType, date: nil)
            let start = schedule!.first!
            let end = schedule!.last!
          
            let hourStart = Calendar.current.component(.hour, from: start)
            let minuteStart = Calendar.current.component(.minute, from: start)
            let hourEnd = Calendar.current.component(.hour, from: end)
            let minuteEnd = Calendar.current.component(.minute, from: end)
            var startComponents = DateComponents()
            startComponents.year = Calendar.current.component(.year, from: date)
            startComponents.month = Calendar.current.component(.month, from: date)
            startComponents.day = Calendar.current.component(.day, from: date)
            startComponents.hour = hourStart - UTCDifference()
            startComponents.minute = minuteStart
            var endComponents = DateComponents()
            endComponents.year = Calendar.current.component(.year, from: date)
            endComponents.month = Calendar.current.component(.month, from: date)
            endComponents.day = Calendar.current.component(.day, from: date)
            endComponents.hour = hourEnd - UTCDifference()
            endComponents.minute = minuteEnd
            let formatter = DateFormatter()
            formatter.timeZone = Calendar.current.timeZone
            formatter.dateFormat = "h:mm a"
            let newStart = Calendar.current.date(from: startComponents)!
            let newEnd = Calendar.current.date(from: endComponents)!
            print(newStart, newEnd)
            startEndLabel.text = "\(formatter.string(from: newStart)) - \(formatter.string(from: newEnd))"
            
            
        } else {
            periodLabel.isHidden = true
            startEndLabel.isHidden = true
            noSchoolLabel.isHidden = false
        }
      
    }
    
  
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if calendarView.visibleDates().indates.count > 0 {
            if calendarView.visibleDates().indates.first!.date < dateRange.first! {
                leftArrow.isHidden = true
            } else {
                leftArrow.isHidden = false
            }
        } else {
            if calendarView.visibleDates().monthDates.first!.date < dateRange.first! {
                leftArrow.isHidden = true
            } else {
                leftArrow.isHidden = false
            }
        }
      
    }
    
   
    @objc func leftTapped() {
        let scrollDate = calendarView.visibleDates().indates.first!.date
        calendarView.scrollToDate(scrollDate)
    }

    @objc func rightTapped() {
         let scrollDate = calendarView.visibleDates().outdates.first!.date
        print(scrollDate)
        calendarView.scrollToDate(scrollDate)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension CalendarViewController: JTAppleCalendarViewDelegate, JTAppleCalendarViewDataSource {
    
    func handleCellConfiguration(view: JTAppleCell?, cellState: CellState) {
        guard let validCell = view as? CalendarCollectionViewCell else {return}
        if cellState.date.noon == Date().noon {
            
            validCell.selectedView.isHidden = false
            validCell.dateLabel.textColor = UIColor.white
            
        } else {
            if validCell.isSelected {
                validCell.dateLabel.textColor = UIColor.white
                 validCell.selectedView.isHidden = false
            } else {
                if cellState.dateBelongsTo == .thisMonth {
                    validCell.dateLabel.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
                } else {
                    validCell.dateLabel.textColor = UIColor.lightGray.withAlphaComponent(0.5)
                }
                validCell.selectedView.isHidden = true
            }
        }
    }
    
    func configureDots(view: JTAppleCell?, cellState: CellState) {
        guard let validCell = view as? CalendarCollectionViewCell else {return}
      
        if !specialDates.contains(cellState.date.noon) {
           
            validCell.dotView.isHidden = true
        } else {
            
            validCell.dotView.isHidden = false
            if cellState.dateBelongsTo == .thisMonth {
                validCell.dotView.backgroundColor = validCell.dotView.backgroundColor
            } else {
                validCell.dotView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
            }

        }
       
    }
  
    func configureDotsWhenScroll(view: JTAppleCalendarView?, visibleDates: DateSegmentInfo) {
        for days in visibleDates.monthDates {
          
            guard let cell = view?.cellForItem(at: days.indexPath) as? CalendarCollectionViewCell else {return}
            if cell.dotView.isHidden == false {
                cell.dotView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
            }
        }
        for days in visibleDates.indates + visibleDates.outdates {
            guard let cell = view?.cellForItem(at: days.indexPath) as? CalendarCollectionViewCell else {return}
            if cell.dotView.isHidden == false {
                cell.dotView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
            }
            
        }
    }
    
    func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
    
        let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "dateCell", for: indexPath) as! CalendarCollectionViewCell
        cell.dateLabel.text = cellState.text
       handleCellConfiguration(view: cell, cellState: cellState)
        configureDots(view: cell, cellState: cellState)
    }
    
    func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {
        
        let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "dateCell", for: indexPath) as! CalendarCollectionViewCell
        cell.dateLabel.text = cellState.text
        handleCellConfiguration(view: cell, cellState: cellState)
         configureDots(view: cell, cellState: cellState)
        return cell
    }
    
    func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
        handleCellConfiguration(view: cell, cellState: cellState)
        configureDayDetail(withDate: date)
        
    }
    
    func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
          handleCellConfiguration(view: cell, cellState: cellState)
    }
    
    func calendar(_ calendar: JTAppleCalendarView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
   
        let date = visibleDates.monthDates.first!.date
        formatter.dateFormat = "MMMM"
        monthLabel.text = formatter.string(from: date).uppercased()
        configureDotsWhenScroll(view: calendar, visibleDates: visibleDates)
        
        if visibleDates.indates.count > 0 {
            if visibleDates.indates.first!.date < dateRange.first! {
               leftArrow.isHidden = true
            } else {
                leftArrow.isHidden = false
            }
        } else {
            if visibleDates.monthDates.first!.date < dateRange.first! {
                leftArrow.isHidden = true
            } else {
                leftArrow.isHidden = false
            }
        }
        
        if visibleDates.outdates.first!.date > dateRange.last! {
            rightArrow.isHidden = true
        } else {
            rightArrow.isHidden = false

        }
        
        
    }
    
    func calendarDidScroll(_ calendar: JTAppleCalendarView) {
        calendarView.deselectAllDates()
    }
    
    
    func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
       
        formatter.dateFormat = "yyyy MM dd"
        formatter.timeZone = Calendar.current.timeZone
        formatter.locale = Calendar.current.locale
        let startDate = formatter.date(from: "2019 08 01")!
        let endDate = formatter.date(from: "2020 08 31")!
        let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate)
        return parameters
    }
    
  
}
<file_sep>//
//  UnderConstructionView.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import MessageUI

class UnderConstructionView: UIView, UIGestureRecognizerDelegate, MFMailComposeViewControllerDelegate {
    @IBOutlet var contentView: UnderConstructionView!
    @IBOutlet weak var underConstructionLabel: UILabel!
    @IBOutlet weak var bottomLabel: UILabel!
    var buttonView = UIView()
    var buttonLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("UnderConstructionView", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
        contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        underConstructionLabel.font = underConstructionLabel.font.withSize(CGFloat(24).relativeToWidth)
        buttonView.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width * 0.45, height: CGFloat(40).relativeToWidth)
        buttonView.center = CGPoint(x: UIScreen.main.bounds.midX, y: bottomLabel.frame.maxY + CGFloat(35).relativeToWidth)
        buttonView.clipsToBounds = true
        buttonView.layer.cornerRadius = buttonView.frame.height / 2
        buttonView.layer.borderWidth = 1
        buttonView.layer.borderColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor
        buttonLabel.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width * 0.45, height: CGFloat(40).relativeToWidth)
        buttonLabel.center = CGPoint(x: UIScreen.main.bounds.width * 0.45 * 0.5, y: CGFloat(40).relativeToWidth / 2)
        buttonLabel.text = "JOIN US"
        buttonLabel.textAlignment = .center
        buttonLabel.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth)
        buttonLabel.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
        buttonView.addSubview(buttonLabel)
        buttonView.bringSubviewToFront(buttonLabel)
        self.addSubview(buttonView)
        buttonView.isUserInteractionEnabled = true
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(joinUsTapped))
        gestureRecognizer.delegate = self
        buttonView.addGestureRecognizer(gestureRecognizer)
    }
    
    @objc func joinUsTapped() {
        buttonView.backgroundColor = UIColor(red:0.82, green:0.82, blue:0.82, alpha: 0.6)
        let address = "<EMAIL>"
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients([address])
            mail.setSubject("Interested in Joining Portola App Team")
            self.parentViewController?.present(mail, animated: true)
            
        } else {
            
        }
        
    }
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        buttonView.backgroundColor = UIColor.white
        self.parentViewController?.dismiss(animated: true)
    }
}
<file_sep>//
//  my_getPeriodsFromToday.swift
//  PHS App
//
//  Created by <NAME> on 7/31/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func my_getPeriodsFromToday(type: Int) -> [String] {
    switch type {
    case 0:
        return defaultDays()
    case 1:
        //pep assembly odd
        return ["1", "A", "PA", "3", "5", "7"]
    case 2:
        //pep assembly even
        return ["2", "A", "PA", "4", "6", "8"]
    case 3:
        //extended lunch odd
        return ["1", "OH", "3", "L", "5", "7"]
    case 4:
        //extended lunch even
        return ["2", "A", "4", "L", "6", "8"]
    case 5:
        //finals type 1
        return ["1", "3", "7"]
    case 6:
        //finals type 2
        return ["5", "6", "8"]
    case 7:
        //finals two periods
        return ["2", "4"]
    case 8:
        //minimum 1-8
        return ["1", "2", "3", "4", "5", "6", "7", "8"]
    case 9:
        //minimum odd
        return ["1", "3", "5", "7"]
    case 10:
        //minimum even
        return ["2", "4", "6", "8"]
    case 11:
        //PSAT 9
        return ["PSAT 9", "OH", "2", "4", "6", "8"]
    case 12:
        //PE testing
        return ["PE 9", "OH", "1", "3", "5", "7"]
    case 13:
        //first 2 days of school
        return ["A", "1", "2", "3", "4", "5", "6", "7", "8"]
    case 14:
        //Hour of Code
        return ["2", "A", "4", "6", "8"]
    case 15:
        //Passion Day
        return ["A", "S1", "S2", "S3"]
    case 16:
        //Pre Testing
        return ["1", "A", "2", "3", "5", "7"]
    case 17:
        //Testing2018/
        return ["TEST", "OH", "4", "6", "8"]
    case 18:
        //CAASPP ODD
        return ["TEST","11", "OH", "1", "3", "5", "7"]
    case 19:
        //CAASPP EVEN
         return ["TEST", "11", "OH", "2", "4", "6", "8"]
    case 20:
        //NO SCHOOL
        return ["NO SCHOOL TODAY"]
    case 21:
        //fine arts assembly
        return ["2", "A/4", "A/4", "6", "8"]
    case 22:
        //monday schedule
         return ["1", "2", "3", "4", "5", "6", "7", "8"]
    case 23:
        //tuesday schedule
          return ["1", "A", "3", "5", "7"]
    case 24:
        //wednesday schedule
         return ["2", "OH", "4", "6", "8"]
    case 25:
        //thursday schedule
          return ["1", "OH", "3", "5", "7"]
    case 26:
        //friday schedule
         return ["2", "A", "4", "6", "8"]
    case 27:
        //thursday advisement
        return ["1", "A", "3", "5", "7"]
    case 28:
        //friday OH
        return ["2", "OH", "4", "6", "8"]
    case 29:
        //Super late start
        return ["2", "4", "6", "8"]
        
    default:
        return defaultDays()
    }
}

func defaultDays() -> [String] {
    switch Calendar.current.component(.weekday, from: Date()) {
    case 1, 7:
        return ["NO SCHOOL TODAY"]
    case 2:
        return ["1", "2", "3", "B", "4", "5", "L", "6", "7", "8"]
    case 3:
        return ["1", "A", "3", "5", "7"]
    case 4:
        return ["2", "OH", "4", "6", "8"]
    case 5:
        return ["1", "OH", "3", "5", "7"]
    case 6:
        return ["2", "A", "4", "6", "8"]
    default: return ["Error"]
    }
}


<file_sep># Portolapp
The iOS Version of the Portolapp, an app to make students' lives easier at Portola High School.


<h2>Features</h2>

Automatic school scheduling

Class start and end reminders

Push notifications for administration

School calendar and bell checks for each day

Digital identification cards with scannable barcodes

Athletics reminders, locations, and times, as well as scores and overall league records

School newspaper publications



<h2>Building</h2>

This is a project based in Swift, meaning that you must install Xcode running on MacOS X, and initialize Cocoapods.\
After pulling from the repository, run ```
pod install ```

in the command line of your choice to install needed dependencies.

After fixing any errors, run the app on the iOS simulator.
<file_sep>//
//  User+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(User)
public class User: NSManagedObject {

}
<file_sep>//
//  PickTeachersViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/19/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreData


class PickTeachersViewController: UIViewController {
    @IBOutlet weak var yourTeachers: UILabel!
    @IBOutlet weak var prevButton: UIButton!
    @IBAction func prevTapped(_ sender: Any) {
        if isFreshLaunch {
            let _ = navigationController?.popViewController(animated: true)
        } else {
            if isSecondScreen {
                dismiss(animated: true)
            }
        }
    }
    @IBOutlet weak var p1label: UILabel!
    @IBOutlet weak var p2Label: UILabel!
    @IBOutlet weak var p3Label: UILabel!
    @IBOutlet weak var p4Label: UILabel!
    @IBOutlet weak var p5Label: UILabel!
    @IBOutlet weak var p6Label: UILabel!
    @IBOutlet weak var p7Label: UILabel!
    @IBOutlet weak var p8Label: UILabel!
    @IBOutlet weak var p1Class: UILabel!
    @IBOutlet weak var p2Class: UILabel!
    @IBOutlet weak var p3Class: UILabel!
    @IBOutlet weak var p4Class: UILabel!
    @IBOutlet weak var p5Class: UILabel!
    @IBOutlet weak var p6Class: UILabel!
    @IBOutlet weak var p7Class: UILabel!
    @IBOutlet weak var p8Class: UILabel!
    @IBOutlet weak var p1TeacherLabel: UILabel!
    @IBOutlet weak var p2TeacherLabel: UILabel!
    @IBOutlet weak var p3TeacherLabel: UILabel!
    @IBOutlet weak var p4TeacherLabel: UILabel!
    @IBOutlet weak var p5TeacherLabel: UILabel!
    @IBOutlet weak var p6TeacherLabel: UILabel!
    @IBOutlet weak var p7TeacherLabel: UILabel!
    @IBOutlet weak var p8TeacherLabel: UILabel!
    
    @IBAction func p1Tapped(_ sender: Any) {
        period = 1
        buttonTapped(period: 1)
    }
    @IBAction func p2Tapped(_ sender: Any) {
        period = 2

        buttonTapped(period: 2)
    }
    @IBAction func p3Tapped(_ sender: Any) {
        period = 3

        buttonTapped(period: 3)
    }
    @IBAction func p4Tapped(_ sender: Any) {
        period = 4

        buttonTapped(period: 4)
    }
    @IBAction func p5Tapped(_ sender: Any) {
        period = 5

        buttonTapped(period: 5)
    }
    @IBAction func p6Tapped(_ sender: Any) {
        period = 6

        buttonTapped(period: 6)
    }
    @IBAction func p7Tapped(_ sender: Any) {
        period = 7

        buttonTapped(period: 7)
    }
    @IBAction func p8Tapped(_ sender: Any) {
        period = 8

        buttonTapped(period: 8)
    }
    
    @IBOutlet weak var p1Button: UIButton!
    @IBOutlet weak var p2Button: UIButton!
    @IBOutlet weak var p3Button: UIButton!
    @IBOutlet weak var p4Button: UIButton!
    @IBOutlet weak var p5Button: UIButton!
    @IBOutlet weak var p6Button: UIButton!
    @IBOutlet weak var p7Button: UIButton!
    @IBOutlet weak var p8Button: UIButton!
    @IBOutlet weak var skipButton: UIButton!
    
    var isPrevButtonHidden = false
    
    @IBAction func skipTapped(_ sender: Any) {
        if isFreshLaunch {
            let ac = UIAlertController(title: "Skip this page?", message: "Entering you teachers can make the app experience more personalized", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Stay", style: .cancel))
            ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { (_) in
                for i in 0...7 {
                    self.myTeachers[i] = nil
                    self.teacherLabels[i].text = "CLICK TO SELECT"
                }
                self.performSegue(withIdentifier: "skipToWelcome", sender: nil)
            }))
            
            present(ac, animated: true)
        } else {
            if isSecondScreen {
                for i in 0...7 {
                    self.myTeachers[i] = nil
                    self.teacherLabels[i].text = "CLICK TO SELECT"
                }
                self.performSegue(withIdentifier: "skipFromSecondScreen", sender: nil)
            } else {
                dismiss(animated: true)
            }
        }
     
        
    }
    @IBAction func nextTapped(_ sender: Any) {
        var shouldPerformSegue = true
        for i in 0...7 {
            if buttons[i].isEnabled == true {
                if myTeachers[i] == nil {
                   let ac = UIAlertController(title: "Missing Fields", message: "Make sure you fill in all your teachers before continuing.", preferredStyle: .alert)
                    ac.addAction(UIAlertAction(title: "OK", style: .cancel))
                    present(ac, animated: true)
                    shouldPerformSegue = false
                } else {
                    continue
                }
            } else {
                continue
            }
        }
        if shouldPerformSegue {
            if isFreshLaunch {
                performSegue(withIdentifier: "finishToWelcome", sender: nil)

            } else {
                if  isPageEditing {
                    performSegue(withIdentifier: "unwindToTeacherPage", sender: nil)
                } else {
                    print("should be here")
                    performSegue(withIdentifier: "newInfoSaved", sender: nil)
                }
            }
        }
    }
    
    override var prefersHomeIndicatorAutoHidden: Bool {
        return true
    }
    
    func buttonTapped(period: Int) {
        if classes[period - 1] == nil {
            subject = "All"
        } else {
            let selectedClass = classes[period - 1]
            if subjects.contains(selectedClass!) {
                subject = selectedClass!
            } else if vapa.contains(selectedClass!) {
                    subject = "VAPA"
                } else if others.contains(selectedClass!) {
                    subject = "General Electives"
            } else if worldLanguage.contains(selectedClass!) {
                subject = "World Language"
            } else if rop.contains(selectedClass!) {
                subject = "ROP"
            } else {
                subject = "All"
            }
            
            }
        
        performSegue(withIdentifier: "pickTeacher", sender: nil)
        
    }
    let subjects = ["English", "Social Studies", "Math", "Physical Education", "Science", "VAPA", "World Language", "General Electives", "ROP", "Sport", "Free Period"]
    var classes = [String?]()
    var buttons = [UIButton]()
    var classLabels = [UILabel]()
    var teacherLabels = [UILabel]()
    var subject = String()
    var period = Int()
    
    var myTeachers = [NewTeachers?]()
    
    var isFreshLaunch = true
    var isSecondScreen = false
    var isPageEditing = false
    
    
    func makeArrays() {
        buttons.append(p1Button)
        buttons.append(p2Button)
        buttons.append(p3Button)
        buttons.append(p4Button)
        buttons.append(p5Button)
        buttons.append(p6Button)
        buttons.append(p7Button)
        buttons.append(p8Button)
        classLabels.append(p1Class)
         classLabels.append(p2Class)
         classLabels.append(p3Class)
         classLabels.append(p4Class)
         classLabels.append(p5Class)
         classLabels.append(p6Class)
         classLabels.append(p7Class)
         classLabels.append(p8Class)
        teacherLabels.append(p1TeacherLabel)
        teacherLabels.append(p2TeacherLabel)
        teacherLabels.append(p3TeacherLabel)
        teacherLabels.append(p4TeacherLabel)
        teacherLabels.append(p5TeacherLabel)
        teacherLabels.append(p6TeacherLabel)
        teacherLabels.append(p7TeacherLabel)
        teacherLabels.append(p8TeacherLabel)
        
        
    }
    
    func autoResizeUI() {
        prevButton.titleLabel!.font = prevButton.titleLabel!.font.withSize(CGFloat(15).relativeToWidth)
        yourTeachers.font = yourTeachers.font.withSize(CGFloat(22).relativeToWidth)
        for label in teacherLabels {
            label.font = label.font.withSize(CGFloat(22).relativeToWidth)
        }
        for label in classLabels {
            label.font = label.font.withSize(CGFloat(14).relativeToWidth)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        makeArrays()
        autoResizeUI()
        for i in 0...classLabels.count - 1 {
            if classes[i] == nil {
                classLabels[i].text = "PERIOD \(i + 1)"
            } else {
                classLabels[i].text = classes[i]!.uppercased()
                if classLabels[i].text == "SPORT" || classLabels[i].text == "FREE PERIOD" {
                    teacherLabels[i].text = "N/A"
                    buttons[i].isEnabled = false
                }
            }
            
        }
        for _ in 0...7 {
            myTeachers.append(nil)
        }
        if !isFreshLaunch {
            skipButton.titleLabel!.text = "CANCEL"
        }
        
        if isPrevButtonHidden {
            prevButton.isHidden = true
        } else {
            prevButton.isHidden = false
        }
    }

    @IBAction func unwindToTeachers(segue: UIStoryboardSegue) {
        if segue.identifier == "backToTeacher" {
            if let source = segue.source as? TeacherPickerViewController {
                let teacher = source.selectedItem
                myTeachers[period - 1] = teacher!
                let teacherLabel = "\(teacher!.first) \(teacher!.last)"
                teacherLabels[period - 1].text = teacherLabel.uppercased()
            }
                
            }
            
        }
    

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "pickTeacher" {
            if let vc = segue.destination as? TeacherPickerViewController {
                switch subject {
                case "All", "General Electives", "ROP":
                    var preparedArray = [NewTeachers]()
                    for classSubjects in subjectsRows {
                        if classSubjects != "ADMINISTRATION" || classSubjects != "SUPPORT STAFF" || classSubjects != "SPECIAL EDUCATION" {
                            let subjectGroup = subjectsDictionary[classSubjects]
                            for teachers in subjectGroup! {
                                preparedArray.append(teachers)
                            }
                        }
                        
                    }
                    vc.teacherObjects = preparedArray
                case "English", "Social Studies", "Math", "Physical Education", "Science", "VAPA", "World Language", "History":
                    var preparedArray = [NewTeachers]()
                    let subjectGroup = subjectsDictionary[subject.uppercased()]
                    for teachers in subjectGroup! {
                       preparedArray.append(teachers)
                    }
                    vc.teacherObjects = preparedArray
                default:
                    var preparedArray = [NewTeachers]()
                    for classSubjects in subjectsRows {
                        if classSubjects != "ADMINISTRATION" || classSubjects != "SUPPORT STAFF" || classSubjects != "SPECIAL EDUCATION" {
                            let subjectGroup = subjectsDictionary[classSubjects]
                            for teachers in subjectGroup! {
                                preparedArray.append(teachers)
                            }
                        }
                        
                    }
                    vc.teacherObjects = preparedArray
                }
            }
          
        } else if segue.identifier == "skipToWelcome" {

        
        } else if segue.identifier == "finishToWelcome" {

            if !classes.contains(nil) {
                for i in 0...7 {
                      let mySchedule = MySchedule(context: PersistentService.context)
                    mySchedule.name = classes[i]
                    mySchedule.period = Int16(i + 1)
                    let currentTeacher = myTeachers[i]
                    let newTeacher = MyNewTeachers(context: PersistentService.context)
                    newTeacher.first = currentTeacher?.first
                    newTeacher.last = currentTeacher?.last
                    newTeacher.subject1 = currentTeacher?.subject1
                    newTeacher.subject2 = currentTeacher?.subject2
                    newTeacher.isFemale = currentTeacher?.isFemale ?? false
                    mySchedule.teacher = newTeacher
                    PersistentService.saveContext()
                    
                }
            }
            
        }
    }
    

}
<file_sep>//
//  Coaches+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(Coaches)
public class Coaches: NSManagedObject {

}
<file_sep>//
//  MySchedule+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 1/6/19.
//  Copyright © 2019 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(MySchedule)
public class MySchedule: NSManagedObject {

}
<file_sep>//
//  Coaches+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension Coaches {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Coaches> {
        return NSFetchRequest<Coaches>(entityName: "Coaches")
    }

    @NSManaged public var first: String?
    @NSManaged public var last: String?
    @NSManaged public var email: String?
    @NSManaged public var gender: Bool
    @NSManaged public var team1: String?
    @NSManaged public var team2: String?

}
<file_sep>//
//  Teachers+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/27/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension Teachers {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Teachers> {
        return NSFetchRequest<Teachers>(entityName: "Teachers")
    }

    @NSManaged public var first: String?
    @NSManaged public var gender: Bool
    @NSManaged public var id: Int32
    @NSManaged public var last: String?
    @NSManaged public var subject1: String?
    @NSManaged public var subject2: String?
    @NSManaged public var myTeacher: NSSet?

}

// MARK: Generated accessors for myTeacher
extension Teachers {

    @objc(addMyTeacherObject:)
    @NSManaged public func addToMyTeacher(_ value: MyTeachers)

    @objc(removeMyTeacherObject:)
    @NSManaged public func removeFromMyTeacher(_ value: MyTeachers)

    @objc(addMyTeacher:)
    @NSManaged public func addToMyTeacher(_ values: NSSet)

    @objc(removeMyTeacher:)
    @NSManaged public func removeFromMyTeacher(_ values: NSSet)

}
<file_sep>//
//  SubjectsExpandableTableViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/17/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import ExpandableCell

class SubjectsExpandableTableViewCell: ExpandableCell {

    @IBOutlet weak var subjectLabel: UILabel!
    static let ID = "expandableCell"
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}
<file_sep>//
//  My_Colors.swift
//  PHS App
//
//  Created by <NAME> on 9/9/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

//var primaryColor = UIColor()
//var secondaryColor = UIColor()
//var darkThemePrimaryColor = UIColor()
//var darkThemeSecondaryColor = UIColor()


<file_sep>//
//  CollectionViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/12/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var iconImageView: UIImageView!
    @IBOutlet weak var iconLabel: UILabel!
    
}
<file_sep>//
//  DetailPickerViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/19/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import PickerView


let worldLanguage = ["Spanish", "French", "Chinese", "Korean", "Latin", "Other"]
let rop = ["Intro to Med Careers", "Sprots Medicine", "Video Production", "Computer Graphics", "Other"]
let vapa = ["Art Studio", "Ceramics", "Arts Survey", "Drawing & Painting", "Visual Imagery", "Computer Graphics",  "Video Production", "Art Portfolio Prep", "AP Art History", "Dance", "Guitar", "Drama", "Tech Theatre", "Studio Music", "Marching Band", "Color Guard", "Band", "Orchestra", "Choir", "Portola Singers", "AP Music Theory", "Other"]
let others = ["ASB", "Health", "Computer Science", "Yearbook", "Adv. Newspaper", "Modern Media",  "Video Production", "Other"]

class DetailPickerViewController: UIViewController {

    enum ItemsType : Int {
        case label, customView
    }
    
    enum PresentationType {
        case numbers(Int, Int), names(Int, Int)
    }
    
 
    
    @IBOutlet weak var navigationBar: UINavigationBar!
  
    @IBOutlet weak var pickerView: PickerView!
 
    @IBAction func cancelTapped(_ sender: Any) {
      dismiss(animated: true)
    }
   
    @IBAction func doneTapped(_ sender: Any) {
        if currentSelectedValue != nil {
            selectedItem = currentSelectedValue!
            performSegue(withIdentifier: "detailBackToClass", sender: nil)
        }
    }
    
   
    var selectedSubject = String()
    var classes = [String]()

    
    
    var presentationType = PresentationType.numbers(0, 0)
    var selectedItem: String?
    var currentSelectedValue: String?
    var updateSelectedValue: ((_ newSelectedValue: String) -> Void)?
    
    var itemsType: PickerViewController.ItemsType = .label
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
        switch selectedSubject {
        case "VAPA":
            classes = vapa
        case "World Language":
            classes = worldLanguage
        case "ROP":
            classes = rop
        case "General Electives":
            classes = others
        default:
            classes = vapa + rop + worldLanguage + others
        }
        configurePicker()
    }
    
    
    
    
    fileprivate func configurePicker() {
        pickerView.delegate = self
        pickerView.dataSource = self
        pickerView.scrollingStyle = .default
        pickerView.selectionStyle = .none
        if let currentSelected = currentSelectedValue, let indexOfCurrentSelectedValue = classes.index(of: currentSelected) {
            pickerView.currentSelectedRow = indexOfCurrentSelectedValue
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */


}


extension DetailPickerViewController: PickerViewDelegate {
    func pickerViewHeightForRows(_ pickerView: PickerView) -> CGFloat {
        
        return 50.0
    }
    
    func pickerView(_ pickerView: PickerView, styleForLabel label: UILabel, highlighted: Bool) {
        
        label.textAlignment = .center
        if (highlighted) {
            label.font = UIFont(name: "Lato-Light", size: CGFloat(28).relativeToWidth)
            label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
        } else {
            label.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth)
            label.textColor = UIColor.lightGray.withAlphaComponent(0.75)
        }
    }
    
    func pickerView(_ pickerView: PickerView, didSelectRow row: Int, index: Int) {
        if self.classes[index] == "Other" {
            currentSelectedValue = selectedSubject
        } else {
            currentSelectedValue = self.classes[index]

        }
    }
}

extension DetailPickerViewController: PickerViewDataSource {
    func pickerView(_ pickerView: PickerView, titleForRow row: Int) -> String {
        return classes[row]
    }
    
    func pickerViewNumberOfRows(_ pickerView: PickerView) -> Int {
        
        return classes.count
    }
    
//    func pickerView(_ pickerView: PickerView, titleForRow row: Int, index: Int) -> String {
//
//        return classes[index]
//    }
    
    
}
<file_sep>//
//  IDCardViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/12/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreData
import RSBarcodes_Swift
import AVFoundation
import LocalAuthentication

class IDCardViewController: UIViewController, UIGestureRecognizerDelegate {
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBAction func dismiss(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBOutlet weak var editButton: UIBarButtonItem!
    @IBAction func editTapped(_ sender: Any) {
        performSegue(withIdentifier: "editNameInput", sender: nil)
    }
    
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var gradeLabel: UILabel!
    @IBOutlet weak var shortID: UILabel!
    @IBOutlet weak var house: UILabel!
    @IBOutlet weak var barcode: UIImageView!
    @IBOutlet weak var longID: UILabel!
    @IBOutlet weak var addCardView: UIView!
    var addCardLabel = UILabel()
//    var thisUser = User(context: PersistentService.context)
    var thisUser = UserInfo()
    @IBOutlet weak var houseHeader: UILabel!
    @IBOutlet weak var gradeHeader: UILabel!
    @IBOutlet weak var shortIDHeader: UILabel!
    @IBOutlet weak var asbView: UILabel!
    @IBOutlet weak var stickerView: UILabel!
    
    var isUserData = false
    
  func faceIDAction() {
    
        let context = LAContext()
        let localizedReasonString = "Secure your information using Face ID and Touch ID."
        var authError: NSError?

        if #available(iOS 8.0, *) {
            
            if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
                 print("I'm here now")
                context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: localizedReasonString) { (success, error) in
                    DispatchQueue.main.async {
                        if success {
                            self.loadIDCard()
                        } else {
                           self.authenticateUsingShortID()
                        }
                    }
                }
            } else {
                authenticateUsingShortID()
            }
        } else {
            
            authenticateUsingShortID()
    }
    }
    
    func loadIDCard() {
        navigationBar.topItem?.rightBarButtonItem?.isEnabled = true
        let subviews: [UIView] = [nameLabel, barcode, gradeHeader, shortIDHeader, houseHeader, gradeLabel, shortID, house, longID, asbView, stickerView]
        for view in subviews {
            UIView.animate(withDuration: 0.5) {
                view.alpha = 1
            }
        }
    }
    
    func authenticateUsingShortID() {
        let ac = UIAlertController(title: "Enter School Short ID", message: "enter short ID to verify your identity.", preferredStyle: .alert)
        ac.addTextField()
        ac.textFields![0].keyboardType = .numberPad
        let submitAction = UIAlertAction(title: "Verify", style: .default, handler: { [unowned ac] _ in
            let answer = ac.textFields![0]
            
            if answer.text != nil {
                if answer.text! == self.shortID.text! {
                    self.loadIDCard()
                } else {
                    self.failVerify(isShortID: true)
                    answer.text = ""
                }
            } else {
                self.failVerify(isShortID: true)
                answer.text = ""
            }
            
            })
        ac.addAction(submitAction)
       
        ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
       
        present(ac, animated: true)
        
    }
    
    func failVerify(isShortID: Bool) {
        var messageString = String()
        if isShortID {
           messageString = "Short ID"
        } else {
            messageString = "Code"
        }
        let ac = UIAlertController(title: "Incorrect \(messageString)", message: "You have entered an incorrect \(messageString), please try again.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { _ in
            if isShortID {
                self.authenticateUsingShortID()
            } else {
                
            }
        }))
        present(ac, animated: true)
    }
    
    
    func autoResizeUI() {
       let subviews: [UIView] = [nameLabel, barcode, gradeHeader, shortIDHeader, houseHeader, gradeLabel, shortID, house, longID, asbView, stickerView]
        for view in subviews {
            view.alpha = 0
        }
        addCardView.alpha = 0
        nameLabel.font = nameLabel.font.withSize(CGFloat(31).relativeToWidth)
        gradeHeader.font = gradeHeader.font.withSize(CGFloat(19).relativeToWidth)
        shortIDHeader.font = shortIDHeader.font.withSize(CGFloat(19).relativeToWidth)
        houseHeader.font = houseHeader.font.withSize(CGFloat(19).relativeToWidth)
        gradeLabel.font = gradeLabel.font.withSize(CGFloat(60).relativeToWidth)
        shortID.font = shortID.font.withSize(CGFloat(60).relativeToWidth)
        house.font = house.font.withSize(CGFloat(60).relativeToWidth)
        longID.font = longID.font.withSize(CGFloat(31).relativeToWidth)
        asbView.isUserInteractionEnabled = true
        asbView.isHidden = true
        stickerView.isHidden = true
        stickerView.isUserInteractionEnabled = true
        let asbGesture = UITapGestureRecognizer(target: self, action: #selector(asbTapped))
        asbGesture.delegate = self
        asbView.addGestureRecognizer(asbGesture)
        
        let stickerGesture = UITapGestureRecognizer(target: self, action: #selector(stickerTapped))
        stickerGesture.delegate = self
        stickerView.addGestureRecognizer(stickerGesture)
    }
    
    @objc func asbTapped() {
        if UserDefaults.standard.bool(forKey: "asbActivated") {
            let ac = UIAlertController(title: "ASB Card", message: "You currenlty have ASB feature activated, you may deactivate it if you wish.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            ac.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in
                let sheet = UIAlertController(title: "Deactivate ASB Feature", message: "Are you sure?", preferredStyle: .actionSheet)
                sheet.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in
                    UserDefaults.standard.set(false, forKey: "asbActivated")
                    self.setStandards()
                }))
                sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
                self.present(sheet, animated: true)

            }))
            present(ac, animated: true)
        } else {
            let ac = UIAlertController(title: "Enter Code", message: "Show your advisement teacher your ID card to activate ASB on this device.", preferredStyle: .alert)
            ac.addTextField()
            let submitAction = UIAlertAction(title: "Verify", style: .default, handler: { [unowned ac] _ in
                let answer = ac.textFields![0]
                
                if answer.text != nil {
                    if answer.text! == "app-activate-asb-now" {
                        UserDefaults.standard.set(true, forKey: "asbActivated")
                        self.setStandards()
                    } else {
                        self.failVerify(isShortID: false)
                        answer.text = ""
                    }
                } else {
                    self.failVerify(isShortID: false)
                    answer.text = ""
                }
                
            })
            ac.addAction(submitAction)
            
            ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
            
            present(ac, animated: true)
        }
       
    }
    
    @objc func stickerTapped() {
        if UserDefaults.standard.bool(forKey: "stickerActivated") {
            let ac = UIAlertController(title: "Sticker", message: "You currenlty have sticker feature activated, you may deactivate it if you wish.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            ac.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in
                let sheet = UIAlertController(title: "Deactivate Sticker Feature", message: "Are you sure?", preferredStyle: .actionSheet)
                sheet.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in
                    UserDefaults.standard.set(false, forKey: "stickerActivated")
                    self.setStandards()
                }))
                sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
                self.present(sheet, animated: true)
            }))
            present(ac, animated: true)

        } else {
            let ac = UIAlertController(title: "Enter Code", message: "Show your advisement teacher your ID card to activate sticker on this device.", preferredStyle: .alert)
            ac.addTextField()
            let submitAction = UIAlertAction(title: "Verify", style: .default, handler: { [unowned ac] _ in
                let answer = ac.textFields![0]
                
                if answer.text != nil {
                    if answer.text! == "app-activate-sticker-now" {
                        UserDefaults.standard.set(true, forKey: "stickerActivated")
                        self.setStandards()
                    } else {
                        self.failVerify(isShortID: false)
                        answer.text = ""
                    }
                } else {
                    self.failVerify(isShortID: false)
                    answer.text = ""
                }
                
            })
            ac.addAction(submitAction)
            
            ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
            
            present(ac, animated: true)
        }
       
    }
    
    func setStandards() {
        if UserDefaults.standard.bool(forKey: "asbActivated") {
            print("asbTrue")
            asbView.font = UIFont(name: "Lato-Bold", size: asbView.font.pointSize)
            asbView.textColor = UIColor(red: 0.376, green: 0.271, blue: 0.529, alpha: 1)
            
        } else {
            print("asbFalse")

            asbView.textColor = UIColor.lightGray
        }
        
        if UserDefaults.standard.bool(forKey: "stickerActivated") {
            print("stickerTrue")

            stickerView.font = UIFont(name: "Lato-Bold", size: asbView.font.pointSize)
            stickerView.textColor = UIColor(red: 0.376, green: 0.271, blue: 0.529, alpha: 1)
        } else {
            print("stickerFalse")
            stickerView.textColor = UIColor.lightGray
        }
        
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()
        let notInitial = UserDefaults.standard.bool(forKey: "isInitial")
        if !notInitial {
           
             UserDefaults.standard.set(true, forKey: "isInitial")
            UserDefaults.standard.set(false, forKey: "asbActivated")
            UserDefaults.standard.set(false, forKey: "stickerActivated")
        }
       
    
      
        
        
        navigationBar.my_setNavigationBar()
        let userRequest: NSFetchRequest<User> = User.fetchRequest()
        do {
            let request = try PersistentService.context.fetch(userRequest)
            if request.count > 0 {
                isUserData = true
                let object = request.first!
               
                if object.first != nil && object.longID > 100000000 {
                    navigationBar.topItem?.rightBarButtonItem?.isEnabled = false
                    thisUser.first = object.first!
                    thisUser.last = object.last!
                    thisUser.longID = object.longID
                    thisUser.shortID = object.shortID
                    thisUser.grade = object.grade
                    thisUser.house = object.house!
                    navigationBar.topItem?.rightBarButtonItem = editButton
                    autoResizeUI()
                    setStandards()
                    
                    gradeLabel.text = String(object.grade)
                    nameLabel.text = "\(object.first!) \(object.last!)"
                    shortID.text = String(object.shortID)
                    house.text = object.house?.uppercased()
                    longID.text = String(object.longID)
                    barcode.image = RSUnifiedCodeGenerator.shared.generateCode(String(object.longID), machineReadableCodeObjectType: AVMetadataObject.ObjectType.code39.rawValue)
                    
                    
                    
                    
                }
                
            } else {
                    isUserData = false
                    navigationBar.topItem?.rightBarButtonItem = nil
                    let subviews: [UIView] = [nameLabel, barcode, gradeHeader, shortIDHeader, houseHeader, gradeLabel, shortID, house, longID, asbView, stickerView]
                    for view in subviews {
                        view.alpha = 0
                    }
                    addCardView.isHidden = false
                    addCardView.alpha = 1
                view.addSubview(addCardView)
                
                }
            
                
            }
             
         catch {
            
        }
       
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if isUserData {
            faceIDAction()
        }
        
        
    }
    
    override func viewWillLayoutSubviews() {
        addCardView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
        addCardView.layer.cornerRadius = addCardView.bounds.height / 2
        addCardLabel.bounds = CGRect(x: 0, y: 0, width: addCardView.frame.width, height: addCardView.frame.height)
        addCardLabel.center = CGPoint(x: addCardView.frame.width / 2, y: addCardView.frame.height / 2)
        addCardLabel.text = "FILL IN YOUR INFO"
        addCardLabel.textAlignment = .center
        addCardLabel.font = UIFont(name: "Lato-Bold", size: CGFloat(17).relativeToWidth)
        addCardLabel.textColor = UIColor.white
        addCardView.addSubview(addCardLabel)
        addCardLabel.my_dropShadow()
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(addCardTapped))
        gestureRecognizer.delegate = self
        addCardView.addGestureRecognizer(gestureRecognizer)
    }
    
   

    @objc func addCardTapped() {
        performSegue(withIdentifier: "showNameInput", sender: nil)
    }
    
    
    
    @IBAction func unwindToIDCard(segue: UIStoryboardSegue) {
        if segue.identifier == "unwindToIDCard" {
        
     
            let updateRequest: NSFetchRequest<User> = User.fetchRequest()
            do {
                let request = try PersistentService.context.fetch(updateRequest)
                
                if let object = request.first {
                    autoResizeUI()
                    thisUser.first = object.first!
                    thisUser.last = object.last!
                    thisUser.longID = object.longID
                    thisUser.shortID = object.shortID
                    thisUser.grade = object.grade
                    thisUser.house = object.house!
                    gradeLabel.text = String(object.grade)
                    nameLabel.text = "\(object.first!) \(object.last!)"
                    shortID.text = String(object.shortID)
                    house.text = object.house?.uppercased()
                    longID.text = String(object.longID)
                    barcode.image = RSUnifiedCodeGenerator.shared.generateCode(String(object.longID), machineReadableCodeObjectType: AVMetadataObject.ObjectType.code39.rawValue)
                    navigationBar.topItem?.rightBarButtonItem = editButton
                    loadIDCard()
                    setStandards()
                    asbView.isUserInteractionEnabled = true
                    stickerView.isUserInteractionEnabled = true

                    
                }
                
            } catch {
                
            }
            
        }
    }

    @IBAction func cancelToIDCard(segue: UIStoryboardSegue) {
        if segue.identifier == "cancelToIDCard" {
            
        }
    }
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showNameInput" {
            if let vc = segue.destination as? NameInputViewController {
                vc.isFreshLaunch = false
            }
        } else if segue.identifier == "editNameInput" {
            if let vc = segue.destination as? NameInputViewController {
                vc.isFreshLaunch = false
                vc.isPageEditing = true
                vc.first = thisUser.first
                vc.last = thisUser.last
                vc.house = thisUser.house
                vc.grade = Int(thisUser.grade)
                vc.shortID = String(thisUser.shortID)
                vc.longID = String(thisUser.longID)
               
            }
        }
    }
 

}
<file_sep>//
//  my_adjustFontSize.swift
//  PHS App
//
//  Created by <NAME> on 8/9/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit
import CoreGraphics


extension CGFloat {
    var relativeToWidth: CGFloat {
        if (self / 375) * UIScreen.main.bounds.width < self {
            return (self / 375) * UIScreen.main.bounds.width
        } else {
            return (self / UIScreen.main.bounds.width) * UIScreen.main.bounds.width
        }
        
    }
    
    var barRelativeToWidth: CGFloat {
        return (self / 375) * UIScreen.main.bounds.width
    }
    
  
}

extension Int {
    var relativeToWidth: Int {
        if (self / 375) * Int(UIScreen.main.bounds.width) < self {
            return Int((self / 375) * Int(UIScreen.main.bounds.width))
        } else {
            return Int((self / Int(UIScreen.main.bounds.width)) * Int(UIScreen.main.bounds.width))
        }
        
    }
    
    var barRelativeToWidth: Int {
        return (self / 375) * Int(UIScreen.main.bounds.width)
    }
    
    
}

<file_sep>//
//  BellScheduleViewController.swift
//  PHS App
//
//  Created by <NAME> on 9/25/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreGraphics
import UserNotifications

class BellScheduleViewController: UIViewController {
    
    var classesRaw = [Int]()
    var bellSchedule = [Date]()
    var classesString = [String]()
    var classesLabels = [UILabel]()
    var timeLabels = [UILabel]()
    
    var progressView = UIView()
    var progress = UIView()
    var day = Calendar.current.component(.day, from: Date())
    var min = Calendar.current.component(.minute, from: Date())
    
    var minimum = CGFloat()
    var maximum =  CGFloat()
    var diff = CGFloat()
    var minOfSchool = numOfMinAtSchool(type: today)
    var minSinceSchool = Date().localTime().minFromSchoolStart()
    var percentage = CGFloat()
    
    let noSchoolLabel = UILabel()
    
    var labelConfigured = false
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)

    }
    
    func patchUserDefaults() {
        //remote notification patch
        let isNotifGranted = UserDefaults.standard.bool(forKey: "notifGranted")
        if !isNotifGranted {
            UserDefaults.standard.set(true, forKey: "notifGranted")
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (isGranted, error) in
                if !isGranted {
                    let ac = UIAlertController (title: "Turn on Notifications", message: "Turn on notifications for Portolapp to receive updates on all things Portola!", preferredStyle: .alert)
                    
                    let settingsAction = UIAlertAction(title: "Yes", style: .default) { (_) -> Void in
                        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                            return
                        }
                        
                        if UIApplication.shared.canOpenURL(settingsUrl) {
                            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                                
                            })
                        }
                    }
                    ac.addAction(settingsAction)
                    let cancelAction = UIAlertAction(title: "No", style: .default, handler: nil)
                    ac.addAction(cancelAction)
                    self.present(ac, animated: true, completion: nil)
                    
                } else {
                    print("notification granted")
                }
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initilize()
        drawProgressLine()
        configureTime()
        configureHoliday()
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        patchUserDefaults()
       
    }
    
    
    @objc func update() {
        if Calendar.current.component(.day, from: Date()) != day {
            day = Calendar.current.component(.day, from: Date())
            
            purge()
            initilize()
            configureTime()
            configureHoliday()
            if today == 20 || !Date().isSchoolDay() || Date() < Date(timeIntervalSince1970: 1566432000) {
                
                if progressView.isHidden == false {
                    progressView.isHidden = true
                }
            } else {
                if progressView.isHidden == true {
                    progressView.isHidden = false
                }
            }
        } else if Calendar.current.component(.minute, from: Date()) != min {
            
            configureTime()
            min = Calendar.current.component(.minute, from: Date())
        }
    
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        progressView.layer.cornerRadius = progressView.bounds.width / 2
        progress.layer.cornerRadius = progress.bounds.height / 2
        if Date().isSchoolDay() && !labelConfigured {
            configureLabels()
         
            labelConfigured = true
            
        }
    }
    
    func initilize() {
        if Date() < Date(timeIntervalSince1970: 1566432000) {
            progressView.isHidden = true
            configureHoliday()
        } else if today != 20 && Date().isSchoolDay() {
            if today == 18 || today == 19 {
              
                bellSchedule.append(my_getSchedule(type: today, date: nil)![0])
              
               
                for i in 0...uniq(source: my_getSchedule(type: today, date: nil)!).count - 1 {
                    if i % 2 == 1 && i < 8 {
                        bellSchedule.append(my_getSchedule(type: today, date: nil)![i])
                    }
                    if i % 2 == 0 && i > 7 {
                        bellSchedule.append(my_getSchedule(type: today, date: nil)![i])
                    }
                }
            } else {
                for i in 0...my_getSchedule(type: today, date: nil)!.count - 1 {
                    if i % 2 == 0 {
                        bellSchedule.append(my_getSchedule(type: today, date: nil)![i])
                    }
                }
            }
          
           
        }
        
        
        if let todayRaw = my_getStartEndPeriodLabel(type: today) {
          
            for i in 0...todayRaw.count - 1 {
                var prev: Int?
                if i > 0 {
                    prev = todayRaw[i - 1]
                } else {
                    prev = nil
                }
                if prev != nil {
                    if todayRaw[i] != prev {
                        classesRaw.append(todayRaw[i])
                    }
                } else {
                    classesRaw.append(todayRaw[i])
                }
            }
          
        }
        
        for classes in classesRaw {
            classesString.append(classes.getPeriodLabel().lowercased().capitalizingFirstLetter())
        }

        
        
        if today != 20 && Date().isSchoolDay() {
        
            percentage = CGFloat(minSinceSchool) / CGFloat(minOfSchool!)
        } else {
            percentage = 0
        }

    }
    
    func drawProgressLine() {
        if today == 20 {
            return
        } else if !Date().isSchoolDay() {
            return
        }
        progressView.bounds = CGRect(x: 0, y: 0, width: CGFloat(40).relativeToWidth, height: CGFloat(500).relativeToWidth)
        progressView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY - CGFloat(30).relativeToWidth)
        progressView.clipsToBounds = true
        progressView.layer.borderWidth = 3
        progressView.layer.borderColor = UIColor.white.cgColor
        view.addSubview(progressView)
        progress.bounds = CGRect(x: 0, y: 0, width: CGFloat(35).relativeToWidth, height: CGFloat(35).relativeToWidth)
        progress.layer.borderWidth = 2.5
        progress.layer.borderColor = UIColor.white.cgColor
        progress.clipsToBounds = true
        progress.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: Int(CGFloat(35).barRelativeToWidth), height: Int(CGFloat(35).barRelativeToWidth))))
        progressView.addSubview(progress)
        
    }
    
    func configureTime() {
        minimum = progressView.bounds.minY + CGFloat(progress.bounds.height.relativeToWidth / 2)
        maximum =  progressView.bounds.maxY - CGFloat(progress.bounds.height.relativeToWidth / 2)
        diff = maximum - minimum
        minOfSchool = numOfMinAtSchool(type: today)
        minSinceSchool = Date().localTime().minFromSchoolStart()
        if today == 20 {
            return
        } else if !Date().isSchoolDay() {
            return
        }
        
        
     
        if Date().timeOfSchoolDay() != nil {
            switch Date().timeOfSchoolDay()! {
            case relativeTime.before:
                progress.center = CGPoint(x: progressView.bounds.midX, y: minimum)
            case relativeTime.during:
                self.progress.center = CGPoint(x: self.progressView.bounds.midX, y: minimum + diff * percentage)
                updateTime()

            case relativeTime.after:
                progress.center = CGPoint(x: progressView.bounds.midX, y: maximum)

            }
        }
       
    }
    
    func updateTime() {
        minimum = progressView.bounds.minY + CGFloat(progress.bounds.height.relativeToWidth / 2)
        maximum =  progressView.bounds.maxY - CGFloat(progress.bounds.height.relativeToWidth / 2)
        diff = maximum - minimum
        minOfSchool = numOfMinAtSchool(type: today)
        minSinceSchool = Date().localTime().minFromSchoolStart()
        percentage = CGFloat(minSinceSchool) / CGFloat(minOfSchool!)
        UIView.animate(withDuration: 1.5) {
            self.progress.center = CGPoint(x: self.progressView.bounds.midX, y: self.minimum + self.diff * self.percentage)
        }
       
    }
    
    func configureLabels() {

        guard bellSchedule.count == classesString.count else {
            print(bellSchedule)
            print(classesString)
            return}
        bellSchedule.append(my_getStartEndTimeFromToday(type: today, dayType: dayType.today, date: nil)[1])
        classesString.append("End Time")
        let top = progressView.frame.minY
        let bottom = progressView.frame.maxY


        let scaleFactor = CGFloat((bellSchedule.count * 2) - 1)
        for i in 0...classesString.count - 1 {
            let label = UILabel()
            label.bounds = CGRect(x: 0, y: 0, width: (progressView.center.x - progressView.frame.width / 2) - CGFloat(30).relativeToWidth, height: (bottom - top) / scaleFactor)
            label.center = CGPoint(x: (progressView.center.x - progressView.frame.width / 2) / 2, y: CGFloat(scaleFactor / 2) + top + (bottom - top) * CGFloat(2 * i) / scaleFactor)
            label.text = classesString[i].uppercased()
            label.textAlignment = .right
            label.textColor = UIColor.white
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.7

            label.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth)
            classesLabels.append(label)
            view.addSubview(label)
            
        }
        for i in 0...bellSchedule.count - 1 {
            let label = UILabel()
            label.bounds = CGRect(x: 0, y: 0, width: (progressView.center.x - progressView.frame.width / 2) - CGFloat(30).relativeToWidth, height: (bottom - top) / scaleFactor)
            label.center = CGPoint(x: self.view.bounds.width - (progressView.center.x - progressView.frame.width / 2) / 2, y: CGFloat(scaleFactor / 2) + top + (bottom - top) * CGFloat(2 * i) / scaleFactor)
            let formatter = DateFormatter()
            formatter.dateFormat = "h:mm a"
            formatter.timeZone = TimeZone(abbreviation: "UTC")
            label.text = formatter.string(from: bellSchedule[i])
            label.textAlignment = .left
            label.textColor = UIColor.white
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.5
         
            label.font = UIFont(name: "Lato-Regular", size: CGFloat(20).relativeToWidth)
            timeLabels.append(label)
            view.addSubview(label)
            
        }
    }
    
    func purge() {
        for labels in classesLabels {
            labels.removeFromSuperview()
        }
        for labels in timeLabels {
            labels.removeFromSuperview()
        }
        classesLabels.removeAll()
        timeLabels.removeAll()
        classesString.removeAll()
        classesRaw.removeAll()
        bellSchedule.removeAll()
    }
    
    func configureHoliday() {
        noSchoolLabel.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: CGFloat(60).relativeToWidth)
        noSchoolLabel.center = CGPoint(x: self.view.center.x, y: self.view.center.y - CGFloat(40).relativeToWidth)
        noSchoolLabel.text = "NO SCHOOL TODAY"
        noSchoolLabel.font = UIFont(name: "Lato-Light", size: CGFloat(30).relativeToWidth)
        noSchoolLabel.textAlignment = .center
        noSchoolLabel.textColor = UIColor.white
        view.addSubview(noSchoolLabel)
        if today == 20 || !Date().isSchoolDay() || Date() < Date(timeIntervalSince1970: 1566432000) {
            noSchoolLabel.isHidden = false
        } else {
            noSchoolLabel.isHidden = true
        }
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension String {
    func capitalizingFirstLetter() -> String {
        return prefix(1).uppercased() + dropFirst()
    }
    
    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}
<file_sep>//
//  SchoolEvents.swift
//  PHS App
//
//  Created by <NAME> on 8/21/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class SchoolEvents: NSObject {
    var date = Date()
    var time = String()
    var title = String()
    var notification = Bool()
    
}
<file_sep>//
//  my_UTCTimeDifference.swift
//  PHS App
//
//  Created by <NAME> on 8/3/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func UTCDifference() -> Int {
    
let offset = Double(TimeZone.current.secondsFromGMT())
    
    return Int(offset / 3600)
    
}
<file_sep>//
//  Date.swift
//  PHS App
//
//  Created by <NAME> on 7/31/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

class SpecialDays: NSObject {
    var date = Date()
    var type = Int()
}
<file_sep>//
//  my_customDateFormatter.swift
//  PHS App
//
//  Created by <NAME> on 7/28/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

extension String {
    func my_customDateFormatter() -> Date {
       let firstArray = self.components(separatedBy: "/")
        if firstArray.count < 3 {
            print(firstArray)
            return Date.distantPast
        }
        
        let year = firstArray[0]
        var month = String()
        var day = String()
        
        if let monthNumber = Int(firstArray[1]) {
            if monthNumber < 1 || monthNumber > 12 {
                return Date.distantPast
            } else if monthNumber < 10 {
                month = "0\(monthNumber)"
            } else {
                month = "\(monthNumber)"
            }
        }
        
        if let dayNumber = Int(firstArray[2]) {
            if dayNumber < 1 || dayNumber > 31 {
                return Date.distantPast
            } else if dayNumber < 10 {
                day = "0\(dayNumber)"
            } else {
                day = "\(dayNumber)"
            }
        }
        
        let stringDate = "\(year)-\(month)-\(day)"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        
        if let date = formatter.date(from: stringDate) {
            return date
        } else {
            return Date.distantPast
        }
        
       
        
        
    }
    

}
<file_sep>//
//  SavedEvents+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/9/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension SavedEvents {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<SavedEvents> {
        return NSFetchRequest<SavedEvents>(entityName: "SavedEvents")
    }

    @NSManaged public var title: String?
    @NSManaged public var time: String?
    @NSManaged public var date: Date
    @NSManaged public var notification: Bool
    @NSManaged public var identifier: String?

}
<file_sep>//
//  ScanViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/14/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import RSBarcodes_Swift
import AVFoundation

class ScanViewController: RSCodeReaderViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.focusMarkLayer.strokeColor = UIColor.yellow.cgColor
        
        self.cornersLayer.strokeColor = UIColor.yellow.cgColor
        
        self.tapHandler = { point in
            print(point)
        }
        
        self.barcodesHandler = { barcodes in
            for barcode in barcodes {
                print("Barcode found: type=" + barcode.type.rawValue + " value=" + barcode.stringValue!)
            }
        }
    }
}
<file_sep>//
//  my_configureTopLabel.swift
//  PHS App
//
//  Created by <NAME> on 8/2/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func timeStringFromDate(date: Date) -> String {
    let formatter = DateFormatter()
    formatter.timeZone = TimeZone(abbreviation: "UTC")
    formatter.dateFormat = "h:mm"
    let startTimeString = formatter.string(from: date)
    return startTimeString
}


<file_sep>//
//  UserInfo.swift
//  PHS App
//
//  Created by <NAME> on 11/24/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class UserInfo: NSObject {
    var first = String()
    var last = String()
    var grade = Int16()
    var house = String()
    var shortID = Int32()
    var longID = Int32()
}
<file_sep>//
//  MyTeachers+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 8/18/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(MyTeachers)
public class MyTeachers: NSManagedObject {
    
}
<file_sep>//
//  NewsTableViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/30/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit

class NewsTableViewCell: UITableViewCell {
    @IBOutlet weak var authorLabel: UILabel!
    @IBOutlet weak var newsTitle: UILabel!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var thumbnail: UIImageView!
    var imageURL: URL?
    
    override func awakeFromNib() {
        super.awakeFromNib()
      
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}
<file_sep>//
//  HousePointsViewController.swift
//  PHS App
//
//  Created by <NAME> on 10/3/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreData

class HousePointsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return houses.count
    }


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let house = houses[indexPath.item]
        
        if let cell = rankCollectionView.dequeueReusableCell(withReuseIdentifier: "rank", for: indexPath) as? HouseRankCollectionViewCell {
            cell.house.text = house.name.uppercased()
            if indexPath.item != 0 {
                cell.house.textColor = cell.house.textColor.withAlphaComponent(0.7)
                cell.points.textColor = cell.points.textColor.withAlphaComponent(0.7)
            }
            cell.points.text = String(house.points)
            return cell
        }
        return UICollectionViewCell()
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: rankCollectionView.bounds.width, height: rankCollectionView.bounds.height / 4 - CGFloat(2.5).relativeToWidth)
    }
    
    var houses = [Houses]()
    var ranksString = ["1st", "2nd", "3rd", "4th"]
    var userHouse: String?

    @IBOutlet weak var houseRankText: UILabel!
    @IBOutlet weak var housePointNumber: UILabel!
    @IBOutlet weak var trophyRank: UIImageView!
    @IBOutlet weak var ranks: UIStackView!
    @IBOutlet weak var rankCollectionView: UICollectionView!
    
    @IBOutlet weak var herPoints: UILabel!
    @IBOutlet weak var ornPoints: UILabel!
    @IBOutlet weak var pegPoints: UILabel!
    @IBOutlet weak var posPoints: UILabel!
    @IBOutlet weak var her: UIView!
    @IBOutlet weak var orn: UIView!
    @IBOutlet weak var peg: UIView!
    @IBOutlet weak var pos: UIView!
    @IBOutlet weak var herHeight: NSLayoutConstraint!
    @IBOutlet weak var ornHeight: NSLayoutConstraint!
    @IBOutlet weak var pegHeight: NSLayoutConstraint!
    @IBOutlet weak var posHeight: NSLayoutConstraint!
    @IBOutlet weak var baseline: UIView!
    
    @IBOutlet weak var rankTrailing: NSLayoutConstraint!
    @IBOutlet weak var baseLineBottom: NSLayoutConstraint!
    
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBAction func dismissTapped(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func refreshTapped(_ sender: Any) {
        houses.removeAll()
        fetchPoints()
        self.rankCollectionView.performBatchUpdates({
            self.rankCollectionView.reloadSections(NSIndexSet(index: 0) as IndexSet)
            
        }) { (_) in
            self.configureGraph(isInitial: false)
            if self.userHouse != nil {
                self.housePointNumber.text = self.defineRank()
            } else {
                 self.housePointNumber.text = "N/A"
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
        fetchPoints()
        rankCollectionView.delegate = self
        rankCollectionView.dataSource = self
        initialize()
        
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.rankTrailing.constant = self.rankTrailing.constant.relativeToWidth
        self.baseLineBottom.constant = self.baseLineBottom.constant.relativeToWidth
        
    }
    
    func defineRank() -> String {
        for i in 0...houses.count - 1 {
            if houses[i].name.lowercased() == userHouse!.lowercased() {
                return ranksString[i]

            }
        }
        return "N/A"
    }
    
    func initialize() {
        herPoints.alpha = 0
        ornPoints.alpha = 0
        pegPoints.alpha = 0
        posPoints.alpha = 0
        herHeight.constant = 0
        ornHeight.constant = 0
        pegHeight.constant = 0
        posHeight.constant = 0
        
        let request: NSFetchRequest<User> = User.fetchRequest()
        do {
            let fetchRequest = try PersistentService.context.fetch(request)
            if let first = fetchRequest.first {
               
                userHouse = first.house
                if userHouse != nil {
                   
                    housePointNumber.text = defineRank()
                    
                } else {
                    let ac = UIAlertController(title: "No Information", message: "We don't know which house you are in. Please fill out your info under Tools -> ID Card.", preferredStyle: .alert)
                    ac.addAction(UIAlertAction(title: "OK", style: .cancel))
                        present(ac, animated: true)
                     self.housePointNumber.text = "N/A"
                }
            } else {
                let ac = UIAlertController(title: "No Information", message: "We don't know which house you are in. Please fill out your info under Tools -> ID Card.", preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .cancel))
                present(ac, animated: true)
                self.housePointNumber.text = "N/A"
            }
            
        } catch {
            
        }
        print("OFIOIFSIEOFJEWIOFIOJEW")
    }
    

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        configureGraph(isInitial: true)
        
    }
    
    func fetchPoints() {
        if CheckInternet.Connection() {
            var name = String()
            var points = Int()

            if let data = try? String(contentsOf: URL(string: "https://spreadsheets.google.com/feeds/list/1XLgfb8kViNMPmgNy9-Gip039e_J6avIpf4k2kD46cNc/od6/public/basic?alt=json")!) {
                let jsonData = JSON(parseJSON: data)
                let entryArray = jsonData.dictionaryValue["feed"]!["entry"].arrayValue
                for entry in entryArray {
                    let house = entry["content"]["$t"].stringValue
                    let finalJSON = house.my_unquotedJSONFormatter(string: house, rows: 2)
                    if finalJSON != "error" {
                        let houseJSON = JSON(parseJSON: finalJSON)
                        let dictionary = houseJSON.dictionaryObject!
                        if let houseGet = dictionary["house"] as? String {
                            name = houseGet
                        }
                        if let pointsGet = dictionary["points"] as? String {
                            points = Int(pointsGet) ?? 1
                        }
                        
                    }
                    let houseObject = Houses()
                    houseObject.name = name
                    houseObject.points = points
                    houses.append(houseObject)
                }
                
            }
        }
        houses.sort { $0.points > $1.points }
    }


    
    
    
    func configureGraph(isInitial: Bool) {
       
        var isZero = Bool()
        var herPoint = Int()
        var ornPoint = Int()
        var pegPoint = Int()
        var posPoint = Int()
        var herPointDiff = Int()
        var ornPointDiff = Int()
        var pegPointDiff = Int()
        var posPointDiff = Int()

        for house in houses {
            if house.points == 0 {
                isZero = true
                break
            } else {
                isZero = false
                continue
            }
        }
        for house in houses {
            switch house.name {
            case "Hercules":
                herPoint = house.points
                herPointDiff = herPoint - (Int(herPoints.text!) ?? herPoint)
                
            case "Orion":
                ornPoint = house.points
                ornPointDiff = ornPoint - (Int(ornPoints.text!) ?? ornPoint)
            case "Pegasus":
                pegPoint = house.points
                pegPointDiff = pegPoint - (Int(pegPoints.text!) ?? pegPoint)
            case "Poseidon":
                posPoint = house.points
                posPointDiff = posPoint - (Int(posPoints.text!) ?? posPoint)
            default: break
            }
        }
        var divisionConstant = CGFloat()
        if self.houses[0].points == 0 {
            print("IS zERO")
            divisionConstant = 1.0
        } else {
             divisionConstant = 1.0
//            print("IS NOT ZERO")
//            print(self.houses[0].points / 10)
//              divisionConstant = CGFloat(1) / CGFloat(self.houses[0].points / 10)
        }
      
        if isInitial {
            
            print(divisionConstant, "THIS")
            UIView.animate(withDuration: 0.7, animations: {
                if isZero {
            
                    self.herHeight.constant = CGFloat(10).relativeToWidth + divisionConstant *  CGFloat(15).relativeToWidth *  (CGFloat(herPoint))
                    self.ornHeight.constant = CGFloat(10).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth *  (CGFloat(ornPoint))
                    self.pegHeight.constant = CGFloat(10).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth *  (CGFloat(pegPoint))
                    self.posHeight.constant = CGFloat(10).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(posPoint))
                    self.view.layoutIfNeeded()
                } else {
                
                    self.herHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(herPoint) - CGFloat(self.houses[self.houses.count - 1].points))
                    self.ornHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(ornPoint) - CGFloat(self.houses[self.houses.count - 1].points))
                    self.pegHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(pegPoint) - CGFloat(self.houses[self.houses.count - 1].points))
                    self.posHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(posPoint) - CGFloat(self.houses[self.houses.count - 1].points))
                    
                    self.view.layoutIfNeeded()
                }
            }) { (_) in
                UIView.animate(withDuration: 0.3, animations: {
                    self.herPoints.text = String(herPoint)
                    self.ornPoints.text = String(ornPoint)
                    self.pegPoints.text = String(pegPoint)
                    self.posPoints.text = String(posPoint)
                    self.herPoints.alpha = 1
                    self.ornPoints.alpha = 1
                    self.pegPoints.alpha = 1
                    self.posPoints.alpha = 1
                })
            }
        } else {
            UIView.animate(withDuration: 0.7, animations: {
                    self.herHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(herPointDiff) * divisionConstant)
                    self.ornHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(ornPointDiff) * divisionConstant)
                    self.pegHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(pegPointDiff) * divisionConstant)
                    self.posHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(posPointDiff) * divisionConstant)
                    self.view.layoutIfNeeded()
               
            }) { (_) in
              
                    self.herPoints.text = String(herPoint)
                    self.ornPoints.text = String(ornPoint)
                    self.pegPoints.text = String(pegPoint)
                    self.posPoints.text = String(posPoint)
                
                
            }
        }
      
    }
    
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  my_getStartEndLabel.swift
//  PHS App
//
//  Created by <NAME> on 8/1/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

func my_getStartEndLabel(type: Int) -> [Bool]? {
    switch type {
    case 0:
        return defaultDaysStartEndLabel()
    case 1, 2:
        //pep assembly odd
        return [false, true, false, false, false, true, false, false, true, false, false, true, false]
    case 3, 4, 14:
        //extended lunch odd and hour of code
        return [false, true, false, false, true, false, false, true, false, false, true, false]

    case 5, 6:
        //finals type 1
        return [false, true, false, true, false]

    case 7:
        //finals two periods
        return [false, true, false]
    case 8:
        //minimum 1-8
        return [false, true, false, true, false, true, false, false, true, false, true, false, true, false, true, false]
    case 9, 10:
        //conferences
        return [false, true, false, false, true, false, true, false]
    case 11, 12:
        //PSAT 9 and PE testing
        return [false, false, true, false, true, false, false, true, false, true, false]

    case 13:
        //first 2 days of school
        return [false, true, false, true, false, true, false, false, true, false, true, false, false, true, false, true, false, true, false]

    case 15:
        //Passion Day
        return [false, true, false, false, true, false, true, false]
    case 16:
        //Pre Testing
        return [false, true, false, false, true, false, true, false, false, true, false, true, false]
    case 17:
        //Testing
        return [false, false, true, false, false, true, false, true, false]
    case 18, 19:
        //CAASPP
        return [false, false, true, false, true, false, true, false, false, false, true, false]
    case 20:
        //NO SCHOOL
        return nil
    case 21:
        //fine arts assembly
        return [false, false, true, false, false, true, false, false, true, false]
    case 22:
        //monday schedule
        return [false, true, false, true, false, false, true, false, true, false, false, true, false, true, false, true, false]
    case 23, 26, 28:
        //tuesday and friday schedule
        return [false, true, false, false, true, false, false, true, false, false, true, false]
    case 24, 25, 27:
        //wednesday and thursday schedule
        return [false, false, false, true, false, false, true, false, false, true, false]
    case 29:
        //super late start
        return [false, true, false, false, true, false, true, false]
   
    default:
        return defaultDaysStartEndLabel()
    }
}

func defaultDaysStartEndLabel() -> [Bool]? {
    switch Calendar.current.component(.weekday, from: Date()) {
    case 1, 7:
        return nil
    case 2:
        return [false, true, false, true, false, false, true, false, true, false, false, true, false, true, false, true, false]
    case 3, 6:
        return [false, true, false, false, true, false, false, true, false, false, true, false]
    case 4, 5:
        return [false, false, false, true, false, false, true, false, false, true, false]

    default: return nil
    }
}
<file_sep>//
//  Today+CoreDataClass.swift
//  PHS App
//
//  Created by <NAME> on 8/8/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData

@objc(Today)
public class Today: NSManagedObject {

}
<file_sep>//
//  IDInputViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/19/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import TextFieldEffects
import RSBarcodes_Swift
import AVFoundation
import CoreData

class IDInputViewController: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate {
    
    @IBOutlet weak var yourID: UILabel!
    @IBOutlet weak var previousButton: UIButton!
    @IBAction func previousTapped(_ sender: Any) {
        if isFreshLaunch {
            _ = navigationController?.popViewController(animated: true)
        } else {
            dismiss(animated: true)
        }
        
    }
    
    @IBOutlet weak var shortIDTextField: HoshiTextField!
    @IBOutlet weak var longIDTextField: HoshiTextField!
    @IBOutlet weak var scanIDView: UIView!
    @IBAction func skipTapped(_ sender: Any) {
        if isFreshLaunch {
            let ac = UIAlertController(title: "Skip this page?", message: "Entering your ID number can save your ID card to your device in case you forget to bring it.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { (_) in
                self.shortID = nil
                self.longID = nil
                self.performSegue(withIdentifier: "skipWelcome", sender: nil)
                
            }))
            ac.addAction(UIAlertAction(title: "Stay", style: .cancel))
            present(ac, animated: true)
        } else {
            performSegue(withIdentifier: "cancelToIDCard", sender: nil)
        }
      
    }
    @IBAction func nextTapped(_ sender: Any) {
        if shortIDTextField.text != nil && longIDTextField != nil {
            shortID = Int(shortIDTextField.text!)
            longID = Int(longIDTextField.text!)
        }
        if shortID != nil && longID != nil {
          
            if isFreshLaunch {
                  saveData()
                performSegue(withIdentifier: "newWelcome", sender: nil)

            } else {
                if isPageEditing {
                    saveEdits()
                    performSegue(withIdentifier: "unwindToIDCard", sender: nil)
                } else {
                    saveData()
                    performSegue(withIdentifier: "unwindToIDCard", sender: nil)
                }
               
            }
        } else {
           let ac = UIAlertController(title: "Missing fields", message: "Make sure you fill in all fields before continuing.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .cancel))
            present(ac, animated: true)
        }
    }
    
    @IBOutlet weak var nextButton: UIButton!
    @IBOutlet weak var skipButton: UIButton!
    func saveData() {
        let user = User(context: PersistentService.context)
        user.first = first
        user.last = last
        user.grade = Int16(grade ?? 0)
        user.house = house
        user.shortID = Int32(shortID ?? 0)
        user.longID = Int32(longID ?? 0)
        PersistentService.saveContext()
    }
    func saveEdits() {
        let updateRequest: NSFetchRequest<User> = User.fetchRequest()
        do {
          let request = try PersistentService.context.fetch(updateRequest)
            if let user = request.first {
                let shortIDEdit = Int32(shortID ?? 0)
                let longIDEdit = Int32(longID ?? 0)
                user.setValue(first, forKey: "first")
                user.setValue(last, forKey: "last")
                user.setValue(grade, forKey: "grade")
                user.setValue(house, forKey: "house")
                user.setValue(shortIDEdit, forKey: "shortID")
                user.setValue(longIDEdit, forKey: "longID")
                PersistentService.saveContext()
            }
        } catch {
            
        }
       
        
    }
    
    var first: String?
    var last: String?
    var grade: Int?
    var house: String?
    var shortID: Int?
    var longID: Int?
    
    var scanLabel = UILabel()
    var barImageView = UIImageView()
    var rescan = UIButton()
    var delete = UIButton()
    var longIDLabel = UILabel()
    
    var isFreshLaunch = true
    var isPageEditing = false 
    
    override var prefersHomeIndicatorAutoHidden: Bool {
        return true
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        yourID.font = yourID.font.withSize(CGFloat(25).relativeToWidth)
        previousButton.titleLabel?.font = previousButton.titleLabel?.font.withSize(CGFloat(15).relativeToWidth)
      
        
        scanLabel.bounds = CGRect(x: 0, y: 0, width: scanIDView.frame.width * 0.8, height: scanIDView.frame.height * 0.8)
        scanLabel.center = CGPoint(x: scanIDView.frame.width / 2, y: scanIDView.frame.height / 2)
        scanLabel.textAlignment = .center
        scanLabel.text = "SCAN ID CARD"
        scanLabel.textColor = UIColor.white
        scanLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(16))
        scanIDView.addSubview(scanLabel)
        scanIDView.clipsToBounds = true
        scanIDView.layer.cornerRadius = scanIDView.frame.width / 2
        scanIDView.backgroundColor = UIColor.white.withAlphaComponent(0)
        scanIDView.layer.borderWidth = 2
        scanIDView.layer.borderColor = UIColor.white.cgColor
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(scanIDTapped))
        gestureRecognizer.delegate = self
        scanIDView.addGestureRecognizer(gestureRecognizer)
        let tap = UITapGestureRecognizer(target: self, action: #selector(screenTapped))
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)
       self.view.addSubview(longIDLabel)
            self.view.addSubview(rescan)
        self.view.addSubview(delete)
        if isFreshLaunch == false {
            skipButton.setTitle("CANCEL", for: .normal)
            nextButton.setTitle("SAVE", for: .normal)
                    }
    }
    

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        if isFreshLaunch == false {
            skipButton.titleLabel!.text = "CANCEL"
        }
        if isPageEditing {
            if shortID != nil {
                shortIDTextField.text = String(shortID!)
            }
            if longID != nil {
                 longIDTextField.text = String(longID!)
                  generateBarcode(string: String(longID!))
            }
           
          
        }

    }
    
    @objc func screenTapped() {
        if shortIDTextField.isEditing || longIDTextField.isEditing {
            if shortIDTextField.text != nil {
                shortID = Int(shortIDTextField.text!)
                shortIDTextField.resignFirstResponder()
            } else {
                shortID = nil
                shortIDTextField.resignFirstResponder()
            }
            if longIDTextField.text != nil {
   
                if CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: longIDTextField.text!)) {
        
                    if let number = Int(longIDTextField.text!) {
                        if number > 100000000 && number < 999999999 {
                            longID = number
                            generateBarcode(string: String(longID!))
                            longIDTextField.resignFirstResponder()
                            
                        } else {
                            let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long", preferredStyle: .alert)
                            ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
                                self.longIDTextField.resignFirstResponder()
                                self.longIDTextField.text = nil
                                
                                
                            }))
                            present(ac, animated: true)
                        }
                    } else {
                        longID = nil
                        
                        longIDTextField.resignFirstResponder()
                        self.barImageView.image = nil
                        self.barImageView.alpha = 0
                        self.rescan.alpha = 0
                        self.delete.alpha = 0
                        self.longIDLabel.alpha = 0
                        self.scanIDView.alpha = 1
                    }
                  
                } else {
               
                    let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long and contain only numbers", preferredStyle: .alert)
                    ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
                        self.longIDTextField.text = nil
                    }))
                    present(ac, animated: true)
                    longIDTextField.resignFirstResponder()
                }
                

            } else {
                longID = nil
                
                longIDTextField.resignFirstResponder()
            }
        }
        
        
        }
        
    

    @objc func scanIDTapped() {
        scanIDView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
        performSegue(withIdentifier: "firstScan", sender: nil)
      
    }
    
    
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == shortIDTextField {
            if textField.text != nil {
               shortID = Int(textField.text!)
            }
            shortIDTextField.resignFirstResponder()
        } else if textField == longIDTextField {
            if textField.text != nil {
                 generateBarcode(string: String(longID!))
                 longID = Int(textField.text!)
            }
          
            longIDTextField.resignFirstResponder()
        }
    }
    
   
    @IBAction func unwindToViewController(segue: UIStoryboardSegue) {
        let source = segue.source as? FirstScanViewController
        scanIDView.backgroundColor = UIColor.white.withAlphaComponent(0)
        if source!.longID != nil {
            if CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: source!.longID!)) {
                longID = Int(source!.longID!)
                if longID! > 100000000 && longID! < 999999999 {
                    generateBarcode(string: String(longID!))
                } else {
                    let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long", preferredStyle: .alert)
                    ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
                        self.longIDTextField.text = nil
                    }))
                    present(ac, animated: true)
                }
            } else {
                let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long and contain only numbers", preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
                    self.longIDTextField.text = nil
                }))
                present(ac, animated: true)
            }
            
        } else {
            self.longID = nil
        }
        
    }

    func generateBarcode(string: String) {
        longIDTextField.text = string

        if let scannedCode = RSUnifiedCodeGenerator.shared.generateCode(string, machineReadableCodeObjectType: AVMetadataObject.ObjectType.code39.rawValue) {
            barImageView.bounds = CGRect(x: 0, y: 0, width: CGFloat(240).relativeToWidth, height: CGFloat(80).relativeToWidth)
            barImageView.center = scanIDView.center
            barImageView.image = scannedCode
            self.view.addSubview(barImageView)
            self.scanIDView.alpha = 0
            longIDLabel.bounds = CGRect(x: 0, y: 0, width: CGFloat(240).relativeToWidth, height: CGFloat(30).relativeToWidth)
            longIDLabel.text = string
            longIDLabel.textColor = UIColor.white
            longIDLabel.font = UIFont(name: "Lato-Light", size: CGFloat(24).relativeToWidth)
            longIDLabel.textAlignment = .center
            
            longIDLabel.center = CGPoint(x: barImageView.center.x, y: barImageView.center.y + CGFloat(60).relativeToWidth)
            rescan.bounds = CGRect(x: 0, y: 0, width: CGFloat(120).relativeToWidth, height: CGFloat(30).relativeToWidth)
            rescan.center = CGPoint(x: barImageView.center.x - CGFloat(50).relativeToWidth, y: barImageView.center.y + CGFloat(120).relativeToWidth)
            rescan.setTitle("Rescan ID Card", for: .normal)
            rescan.titleLabel!.font = UIFont(name: "Lato-Light", size: CGFloat(15).relativeToWidth)
            rescan.titleLabel!.textColor = UIColor.white
            rescan.titleLabel!.textAlignment = .center
            
            rescan.addTarget(self, action: #selector(rescanTapped), for: .touchUpInside)
            
            delete.bounds = CGRect(x: 0, y: 0, width: CGFloat(120).relativeToWidth, height: CGFloat(30).relativeToWidth)
            delete.center = CGPoint(x: barImageView.center.x + CGFloat(75).relativeToWidth, y: barImageView.center.y + CGFloat(120).relativeToWidth)
            delete.setTitle("Discard", for: .normal)
            delete.titleLabel!.font = UIFont(name: "Lato-Light", size: CGFloat(15).relativeToWidth)
            delete.titleLabel!.textColor = UIColor.white
            delete.titleLabel!.textAlignment = .center
            
            delete.addTarget(self, action: #selector(deleteTapped), for: .touchUpInside)
            self.barImageView.alpha = 1
            self.rescan.alpha = 1
            self.delete.alpha = 1
            self.longIDLabel.alpha = 1
            
        }
        
    }
    
    @objc func rescanTapped() {
             performSegue(withIdentifier: "firstScan", sender: nil)
    }
    
    @objc func deleteTapped() {
        let ac = UIAlertController(title: "Discard Scanned ID Card?", message: "Are you sure you want to delete this card?", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (_) in
            self.longIDTextField.text = nil
            self.barImageView.image = nil
            self.barImageView.alpha = 0
            self.rescan.alpha = 0
            self.delete.alpha = 0
            self.longIDLabel.alpha = 0
            self.scanIDView.alpha = 1
        }))
       ac.addAction(UIAlertAction(title: "No", style: .cancel))
        present(ac, animated: true)
    }

 
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  my_nextMonday.swift
//  PHS App
//
//  Created by <NAME> on 8/2/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

extension Date {
    func nextMonday() -> Date {
        var dayToAdd = Int()
        switch Calendar.current.component(.weekday, from: self) {
            case 1:
                dayToAdd = 1
            case 2:
                dayToAdd = 7
            case 3:
            dayToAdd = 6

            case 4:
            dayToAdd = 5

            case 5:
            dayToAdd = 4

            case 6:
            dayToAdd = 3

            case 7:
            dayToAdd = 2
        default:
            dayToAdd = 9 - Calendar.current.component(.weekday, from: self)

        }
        
       
        
        let date = Calendar.current.date(byAdding: .day, value: dayToAdd, to: self)
        return date!
    }
}
<file_sep>//
//  AthleticsDetailViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/20/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import Segmentio
import UserNotifications

class AthleticsDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if upcomingGames.count >= 3 {
            return 3
        } else {
            return upcomingGames.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.main.bounds.width, height: upcomingView.frame.height / 3)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = upcomingView.dequeueReusableCell(withReuseIdentifier: "upcoming", for: indexPath) as! UpcomingGamesCollectionViewCell
        let game = upcomingGames[indexPath.item]
        cell.PortolaLabel.text = "PORTOLA"
     
        cell.purpleCircle.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
        cell.purpleCircle.layer.cornerRadius = 35
        cell.purpleCircle.my_dropShadow()
        cell.grayCircle.backgroundColor = UIColor(red:0.68, green:0.68, blue:0.68, alpha:1.0)
        cell.grayCircle.layer.cornerRadius =  35
        cell.grayCircle.my_dropShadow()
        cell.awayInitial.text = String(Array(game.other!).first!)
        cell.awayLabel.text = game.other?.uppercased()
        cell.team.text = "VARSITY"
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM. dd"
        cell.date.text = formatter.string(from: game.time).uppercased()
        if game.isAway {
            cell.location.text = "AWAY"
        } else {
            cell.location.text = "HOME"
        }
        
        return cell
        
        
    }
    
    
    
    @IBAction func refreshTapped(_ sender: Any) {
        schedule.removeAll()
        performSelector(inBackground: #selector(loadSchedule), with: nil)
    }
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var segmentioView: Segmentio!
    var content = [SegmentioItem]()
    
    @IBAction func backTapped(_ sender: Any) {
        dismiss(animated: true)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return schedule.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = Bundle.main.loadNibNamed("GameScheduleTableViewCell", owner: self, options: nil)?.first as? GameScheduleTableViewCell {
            cell.sport = sport
            let game = schedule[indexPath.row]
            let dateFormatter = DateFormatter()
            dateFormatter.timeZone = Calendar.current.timeZone
            dateFormatter.dateFormat = "M/dd"
            cell.date.text = dateFormatter.string(from: game.time)
            let weekFormatter = DateFormatter()
            weekFormatter.timeZone = Calendar.current.timeZone
            weekFormatter.dateFormat = "EEEE"
            let weekdayString = weekFormatter.string(from: game.time).uppercased()
            cell.weekday.text = weekdayString
            let timeFormatter = DateFormatter()
            timeFormatter.timeZone = Calendar.current.timeZone
            timeFormatter.dateFormat = "h:mm a"
            let timeString = timeFormatter.string(from: game.time)
            cell.time.text = timeString
            if game.isAway {
                cell.isAway.text = "AWAY"
            } else {
                cell.isAway.text = "HOME"
            }
            cell.gameTime = game.time
            cell.identifier = "\(sport)\(Calendar.current.component(.day, from: game.time))\(Calendar.current.component(.month, from: game.time))"
            UNUserNotificationCenter.current().getPendingNotificationRequests { request in
                for notification in request {
                    if cell.identifier == notification.identifier {
                        cell.notification = true
                        DispatchQueue.main.async {
                            cell.bell.alpha = 1
                            
                        }
                        break
                    } else {
                        cell.notification = false
                        DispatchQueue.main.async {
                            cell.bell.alpha = 0
                        }
                    }
                }
            }
            if game.homeScore != nil && game.awayScore != nil {
               
                cell.gameScheduleView.alpha = 0
                cell.gameResultView.alpha = 1
                cell.homeScore.text = String(game.homeScore!)
                cell.awayScore.text = String(game.awayScore!)
                if game.isAway {
                    cell.homeTeam.text = game.other?.uppercased()
                    cell.otherTeam = game.other ?? " "
                    cell.awayTeam.text = "PORTOLA"
                } else {
                    cell.homeTeam.text = "PORTOLA"
                    cell.otherTeam = game.other ?? " "
                    cell.awayTeam.text = game.other?.uppercased()
                }
                
            } else {
                cell.gameScheduleView.alpha = 1
                cell.gameResultView.alpha = 0
                cell.sendSubviewToBack(cell.gameResultView)
                cell.awayTeamSchedule.text = game.other?.uppercased()
                cell.otherTeam = game.other ?? " "
                
            }
            return cell
        } else {
            return UITableViewCell()
        }
        
       
    }
    
    var sport = String()

    @IBOutlet weak var scheduleView: UITableView!
    var schedule = [Games]()
    var upcomingGames = [Games]()
    
    @IBOutlet weak var homeView: UIView!
    @IBOutlet weak var upcomingView: UICollectionView!
    
    
    @IBOutlet weak var overall: UILabel!
    @IBOutlet weak var record: UILabel!
    @IBOutlet weak var varsity: UILabel!
    @IBOutlet weak var upcoming: UILabel!
    @IBOutlet weak var nothingLabel: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.topItem!.title = sport
        record.alpha = 0
        nothingLabel.alpha = 0
        navigationBar.my_setNavigationBar()
        scheduleView.delegate = self
        scheduleView.dataSource = self
        upcomingView.delegate = self
        upcomingView.dataSource = self
        setSegmentedControl()
        segmentioView.selectedSegmentioIndex = 0
        homeView.frame = CGRect(x: 0, y: segmentioView.frame.maxY, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - segmentioView.frame.maxY)
        record.font = record.font.withSize(CGFloat(58).relativeToWidth)
        overall.font = overall.font.withSize(CGFloat(19).relativeToWidth)
        varsity.font = varsity.font.withSize(CGFloat(18).relativeToWidth)
        upcoming.font = upcoming.font.withSize(CGFloat(19).relativeToWidth)
      
        view.addSubview(scheduleView)
        view.bringSubviewToFront(homeView)
         view.bringSubviewToFront(segmentioView)
        performSelector(inBackground: #selector(loadSchedule), with: nil)
        let layout = self.upcomingView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumLineSpacing = -10
    
      
        
        
        
    }
    
    @objc func loadSchedule() {
   
        if CheckInternet.Connection() {
            
            if let data = try? String(contentsOf: URL(string: "https://portola.epicteam.app/api/sports")!) {
                
                let jsonData = JSON(parseJSON: data)
                
                if let array = jsonData.dictionaryValue["sports"]?.arrayValue {
                    
                    for item in array {
                        
                        if let parsedInfo = item.dictionaryObject {
                            if let name = parsedInfo["name"] as? String {
                              
                                if name == sport {
                                  
                                   
                                            let game = Games()
                                            game.sport = sport
                                            if let date = parsedInfo["when"] as? String {
                                              
                                               
                                                    let formatter = DateFormatter()
                                                    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
                                                    game.time = formatter.date(from: date) ?? Date.distantPast
                                                
                                                
                                            }
                                            if let opponent = parsedInfo["other"] as? String {
                                                game.other = opponent
                                            } else {
                                                game.other = nil
                                            }
                                            if let isAway = parsedInfo["is_away"] as? Bool {
                                                game.isAway = isAway
                                            }
                                            if let home = parsedInfo["home_score"] as? Int {
                                                game.homeScore = home
                                            } else {
                                                game.homeScore = nil
                                            }
                                            if let away = parsedInfo["away_score"] as? Int {
                                                game.awayScore = away
                                            } else {
                                                game.awayScore = nil
                                            }
                                            schedule.append(game)
                                    
                                    if game.time > Date() {
                                        upcomingGames.append(game)
                                    }
                                    
                                } else {
                                    continue
                                }
                        }
                       
                            
                        }
                    }
                    schedule = schedule.sorted(by: { $0.time < $1.time } )
                    upcomingGames = upcomingGames.sorted(by: {$0.time < $1.time})
                }
              
                
            }
            DispatchQueue.main.async {
                self.scheduleView.reloadData()
                self.upcomingView.reloadData()
                self.configureHome()

            }
            
        } else {
            let ac = UIAlertController(title: "No Internet Connection", message: "Cannot load schedule because there is no internet connection.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (_) in
                self.dismiss(animated: true)
            }))
        }
    }
    
    func configureHome() {
        var wins = 0
        var losses = 0
        var ties: Int? = nil
        for games in schedule {
            if games.homeScore != nil && games.awayScore != nil {
                if games.isAway {
                    if games.homeScore! < games.awayScore! {
                        if sport == "Girls Golf" || sport == "Boys Golf" {
                            losses += 1
                        } else {
                            wins += 1
                        }
                    } else if games.homeScore! > games.awayScore! {
                        if sport == "Girls Golf" || sport == "Boys Golf" {
                            wins += 1
                        } else {
                            losses += 1
                        }
                        
                    } else {
                        if ties == nil {
                            ties = 1
                        } else {
                            ties! += 1
                        }
                    }
                } else {
                    if games.homeScore! > games.awayScore! {
                        if sport == "Girls Golf" || sport == "Boys Golf" {
                            losses += 1
                        } else {
                            wins += 1
                        }
                    } else if games.homeScore! < games.awayScore! {
                        if sport == "Girls Golf" || sport == "Boys Golf" {
                            wins += 1
                        } else {
                            losses += 1
                        }
                        
                    } else {
                        if ties == nil {
                            ties = 1
                        } else {
                            ties! += 1
                        }
                    }
                }
            }
        }
        if ties == nil {
            record.text = "\(wins)-\(losses)"
        } else {
            record.text = "\(wins)-\(ties!)-\(losses)"
        }
        record.alpha = 1
        if upcomingGames.count == 0 {
            nothingLabel.alpha = 1
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        segmentioView.valueDidChange = { segmentio, segmentIndex in
            switch segmentIndex {
            case 0:
               self.view.sendSubviewToBack(self.scheduleView)
            case 1:
                self.view.bringSubviewToFront(self.scheduleView)

            default:
                break
            }
        }
    }
    
    func setSegmentedControl() {
        
        view.addSubview(segmentioView)
        let position = SegmentioPosition.dynamic
        let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white)
        let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none)
        let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0))
        segmentioView.selectedSegmentioIndex = 0
        let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: (
            defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)),
            selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white),
            highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white)
            )
            ,animationDuration: 0.2)
        let home = SegmentioItem(title: "HOME", image: nil)
        let schedule = SegmentioItem(title: "SCHEDULE", image: nil)
        
        content = [home, schedule]
        segmentioView.setup(content: content, style: .onlyLabel, options: options)
        
    }
    
    
  

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
<file_sep>//
//  MyTeachers+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 8/27/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension MyTeachers {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<MyTeachers> {
        return NSFetchRequest<MyTeachers>(entityName: "MyTeachers")
    }

    @NSManaged public var period: Int16
    @NSManaged public var teacher: Teachers?

}
<file_sep>//
//  my_isDuringSchool.swift
//  PHS App
//
//  Created by <NAME> on 8/4/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation

enum relativeTime {
    case before
    case during
    case after
}

extension Date {
    func getRelativeTime() -> relativeTime? {
        let currentTime = self.localTime()
       
            if currentTime.isSchoolDay() {
                
                let type = getDayType(date: currentTime)
                let schedule = my_getSchedule(type: type, date: currentTime)!
                
                let start = schedule.first!
                let end = schedule.last!
               
                if currentTime < start {
                   
                    return .before
                } else if currentTime >= end {
                    
                    return .after
                } else {
                     
                    return .during
                }
                
            } else {
               
                return nil
            }
        
     
    }
}
<file_sep>//
//  my_boolToLabel.swift
//  PHS App
//
//  Created by <NAME> on 8/2/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
extension Bool {
    func startEndLabelFromBool() -> String {
        if self {
            return "STARTS"
        } else {
            return "ENDS"
        }
    }
}
<file_sep>//
//  my_unquotedJSONFormatter.swift
//  PHS App
//
//  Created by <NAME> on 7/28/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit

extension String {
    func my_unquotedJSONFormatter(string: String, rows: Int) -> String {
        
        var finalString = ""
        var isComma = false
        let firstArray = string.components(separatedBy: ", ")
    
      
            if firstArray.count != rows {
                print("error: \(firstArray)")
                return "error"
                
            }
      
       
        var secondArray = [String]()
        for item in firstArray {
            let individual = item.components(separatedBy: ": ")
            for key in individual {
                secondArray.append(key)
            }
        }
        
        if secondArray.count != rows * 2 {
            print("error: \(secondArray)")
            return "error"
        } else {
            finalString += "{ "
            for i in 0...secondArray.count - 2 {
                if isComma {
                    finalString += "\"\(secondArray[i])\", "
                } else {
                    finalString += "\"\(secondArray[i])\": "
                }
                isComma = !isComma
            }
            
            finalString += "\"\(secondArray[secondArray.count - 1])\" }"
        }
        
        
//         finalString = "{ \"\(secondArray[0])\": \"\(secondArray[1])\", \"\(secondArray[2])\": \"\(secondArray[3])\", \"\(secondArray[4])\": \"\(secondArray[5])\", \"\(secondArray[6])\": \"\(secondArray[7])\" }"
        
     

        return finalString
        
    }
    
    
    static func createFormattedJSON() -> String? {
        let string = String()
        let rows = Int()
        let finalString = string.my_unquotedJSONFormatter(string: string, rows: rows)
        return finalString
        
    }

}

<file_sep>//
//  NewTeachers.swift
//  PHS App
//
//  Created by <NAME> on 1/6/19.
//  Copyright © 2019 Portola App Development. All rights reserved.
//

import UIKit

class NewTeachers: NSObject {
    var id = Int()
    var first = String()
    var last = String()
    var subject1 = String()
    var subject2: String?
    var isFemale = Bool()
}
<file_sep>//
//  ViewController.swift
//  PHS App
//
//  Created by <NAME> on 7/22/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import CoreGraphics
//import XLActionController


class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

  
    var isFreshLaunch = true
    var safeArea = CGFloat() 
    @IBOutlet weak var navigationBackground: UIImageView!
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var collectionView: UICollectionView!
    
    let icons = ["Clubs", "Teachers", "ID Card", "Call", "Calendar", "Portola Pilot", "PNN"]
    let iconImages: [UIImage] = [
        UIImage(named: "clubs")!,
        UIImage(named: "teachers")!,
        UIImage(named: "id")!,
        UIImage(named: "call")!,
        UIImage(named: "calendar")!,
        UIImage(named: "pilot")!,
        UIImage(named: "pnn")!,
        UIImage(named: "housePoints")!
    ]
    
    let currentIcons = ["Teachers", "ID Card", "Call", "Calendar", "Portola Pilot", "House Points"]
    let currentIconImages: [UIImage] = [
        UIImage(named: "teachers")!,
        UIImage(named: "id")!,
        UIImage(named: "call")!,
        UIImage(named: "calendar")!,
        UIImage(named: "pilot")!,
        UIImage(named: "housePoints")!
    ]
    
    override func viewWillAppear(_ animated: Bool) {
        if isFreshLaunch {
            self.tabBarController!.selectedIndex = 1
            isFreshLaunch = false
        }
        
        for cell in collectionView.indexPathsForSelectedItems ?? [] {
            collectionView.deselectItem(at: cell, animated: true)
            let deselectedCell = collectionView.cellForItem(at: cell)
            deselectedCell?.backgroundColor = UIColor.white
        }
        
    }
    


    
   
    
   
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.allowsMultipleSelection = false
        drawLines()
        let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: (self.view.bounds.width) / 2, height: safeArea / 4)
        
        
    }
    
    
    
    func drawLines() {
        let safeTopY = navigationBar.bounds.maxY - (20 - UIApplication.shared.statusBarFrame.height)
       
        var bottomConstant = 0
        if UIScreen.main.bounds.height == 812 {
            bottomConstant = 34
        }
        let safeBottomY = tabBarController!.tabBar.frame.minY - CGFloat(bottomConstant)
        safeArea = safeBottomY - safeTopY
        
        let renderer1 = UIGraphicsImageRenderer(size: CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        let img1 = renderer1.image { ctx in
            ctx.cgContext.setStrokeColor(UIColor(red:0.82, green:0.70, blue:0.88, alpha:1.0).cgColor)
            ctx.cgContext.setLineWidth(0.5)
            
            ctx.cgContext.move(to: CGPoint(x: self.view.bounds.midX, y: navigationBar.frame.maxY  - (20 - UIApplication.shared.statusBarFrame.height)) )
            ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.midX, y: self.view.bounds.height))
            ctx.cgContext.move(to: CGPoint(x: 0, y: safeTopY + safeArea / 2))
            ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.maxX, y: safeTopY + safeArea / 2))
            ctx.cgContext.move(to: CGPoint(x: 0, y: safeTopY + safeArea / 4))
            ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.maxX, y: safeTopY + safeArea / 4))
            ctx.cgContext.move(to: CGPoint(x: 0, y: safeTopY + safeArea / 4 * 3))
            ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.maxX, y: safeTopY + safeArea / 4 * 3))
     
            ctx.cgContext.drawPath(using: .stroke)
        }
         let image = UIImageView(image: img1)
        image.image = img1
       
        
        
        }

    func callNumber(number: String) {
         let numberString = number
        guard let url = URL(string: "telprompt://\(numberString)") else {
           
            return
            
        }
        UIApplication.shared.open(url)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return currentIcons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
        cell.iconLabel.text = currentIcons[indexPath.item]
        cell.iconImageView.image = currentIconImages[indexPath.item]
        if currentIcons[indexPath.item] == "Clubs" {
            cell.iconLabel.textColor = UIColor.gray
        }
        
        return cell
    }
    

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        if let item = cell as? CollectionViewCell {
            if item.iconLabel.text != "Call" {
                cell?.layer.backgroundColor = UIColor(red:0.82, green:0.82, blue:0.82, alpha: 0.6).cgColor
            }
        }
        
        let cellItem = cell as! CollectionViewCell
        switch cellItem.iconLabel.text! {
        case "Call":
            let ac = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            ac.addAction(UIAlertAction(title: "Front Office", style: .default, handler: { (_) in
            self.callNumber(number: "9499368200")
        }))
            ac.addAction(UIAlertAction(title: "Attedance Office", style: .default, handler: { (_) in
            self.callNumber(number: "9499368201")
        }))
            ac.addAction(UIAlertAction(title: "Counseling Office", style: .default, handler: { (_) in
            self.callNumber(number: "9499368227")
        }))
            ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
            
            present(ac, animated: true)
            
            
        default:
            let vc = storyboard?.instantiateViewController(withIdentifier: cellItem.iconLabel.text!)
            present(vc!, animated: true)

        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.backgroundColor = UIColor.white.cgColor
    }
    
    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell {
         if cell.iconLabel.text == "Call" {
                if cell.isSelected {
                    collectionView.deselectItem(at: indexPath, animated: true)
                    return true
                }
            } else {
                return true
                }
        }
       return true
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

<file_sep>//
//  MyTeachersTableViewCell.swift
//  PHS App
//
//  Created by <NAME> on 8/20/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import MessageUI

class MyTeachersTableViewCell: UITableViewCell, MFMailComposeViewControllerDelegate {
    @IBOutlet weak var circleView: UIView!
    @IBOutlet weak var initialsLabel: UILabel!
    @IBOutlet weak var periodLabel: UILabel!
    @IBOutlet weak var teacherLabel: UILabel!
    @IBOutlet weak var classLabel: UILabel!
    @IBOutlet weak var emailImageView: UIImageView!
    @IBOutlet weak var emailButtonView: UIView!
    var first = String()
    var last = String()
    var gender = Bool()
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        circleView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
        circleView.layer.cornerRadius = 25
        emailButtonView.layer.cornerRadius = 25
        emailButtonView.layer.borderWidth = 2
        emailButtonView.layer.borderColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor
        
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(emailTapped))
        gestureRecognizer.delegate = self
        emailButtonView.addGestureRecognizer(gestureRecognizer)
        
        teacherLabel.text = "\(first.uppercased()) \(last.uppercased())"
        circleView.my_dropShadow()
        
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        circleView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)
    }
    
    @objc func emailTapped() {
        emailButtonView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.45)
        var address = String()
        let trimmedLast = last.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: " ", with: "")
        
            address = "\(first)\(trimmedLast)@<EMAIL>"
       
        sendEmail(address: address, isFemale: gender, lastName: last)
    }
    
    func sendEmail(address: String, isFemale: Bool, lastName: String) {
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients([address])
            var title = String()
                if isFemale {
                    title = "Ms."
                } else {
                    title = "Mr."
                }
            
            
            mail.setMessageBody("<p>Hello, \(title) \(lastName), <br><br><br> <br>Sincerely,", isHTML: true)
            self.parentViewController?.present(mail, animated: true)
        } else {
            
        }
    }
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        emailButtonView.backgroundColor = UIColor.white
        self.parentViewController?.dismiss(animated: true)
    }
    
    
    

}
<file_sep>//
//  MySchedule+CoreDataProperties.swift
//  PHS App
//
//  Created by <NAME> on 1/6/19.
//  Copyright © 2019 Portola App Development. All rights reserved.
//
//

import Foundation
import CoreData


extension MySchedule {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<MySchedule> {
        return NSFetchRequest<MySchedule>(entityName: "MySchedule")
    }

    @NSManaged public var period: Int16
    @NSManaged public var name: String?
    @NSManaged public var teacher: MyNewTeachers?

}
<file_sep>//
//  my_isLongBreak.swift
//  PHS App
//
//  Created by <NAME> on 9/4/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import Foundation
import UIKit
//FOR NOTIFICATION PURPOSES ONLY
extension Date {
    var isLongBreak: Bool {
        switch Calendar.current.component(.month, from: self) {
        case 11:
            if Calendar.current.component(.day, from: self) == 22 || Calendar.current.component(.day, from: self) == 23 {
                return true
            } else {
                return false
            }
        case 12:
            if Calendar.current.component(.day, from: self) >= 25 && Calendar.current.component(.day, from: self) <= 31 {
                return true
            } else
            {
                return false
            }
        case 1:
            if Calendar.current.component(.day, from: self) >= 1 && Calendar.current.component(.day, from: self) <= 4 {
                return true
            } else {
                return false
            }
        case 4:
            if Calendar.current.component(.day, from: self) >= 1 && Calendar.current.component(.day, from: self) <= 5 {
                return true
            } else {
                return false
            }
        default: return false
            
        }
       
    }
}
<file_sep>//
//  PortolaPilotViewController.swift
//  PHS App
//
//  Created by <NAME> on 8/13/18.
//  Copyright © 2018 Portola App Development. All rights reserved.
//

import UIKit
import SwiftyXMLParser
import Segmentio
import SDWebImage



class PortolaPilotViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return current.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let article = current[indexPath.row]
           let cell = Bundle.main.loadNibNamed("NewsTableViewCell", owner: self, options: nil)?.first as! NewsTableViewCell
            cell.newsTitle.text = article.title
            cell.authorLabel.text = article.author
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yy"
        formatter.timeZone = Calendar.current.timeZone
        formatter.locale = Calendar.current.locale
            cell.dateLabel.text = formatter.string(from: article.pubDate)
        if article.imageLink != nil {
            cell.thumbnail.sd_setImage(with: article.imageLink, placeholderImage: UIImage(named: "newsPlaceholder"))
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! NewsTableViewCell
        let article = current[indexPath.row]
        if let vc = storyboard?.instantiateViewController(withIdentifier: "newsDetail") as? NewsDetailViewController {
            vc.titleText = cell.newsTitle.text!
            vc.info = "By \(cell.authorLabel.text!) on \(cell.dateLabel.text!)."
            vc.imageLink = article.imageLink
            vc.news = article.content
            vc.storyLink = article.link
            if let navigator = navigationController {
                navigator.pushViewController(vc, animated: true)
            } else {
                print("no navigation controller")
            }
        } else {
            print("no view controller")
        }
       
        
 
     
        
        
    }

    var content = [SegmentioItem]()
    
    var articles = [NewsArticle]()
    var groupDictionary = [String: [NewsArticle]]()
    var groupCategories = [String]()
    var current = [NewsArticle]()
    
    var indicator = UIActivityIndicatorView()
    
    @IBOutlet weak var segmentioView: Segmentio!
    @IBOutlet weak var newsTableView: UITableView!
    
    @IBAction func dismiss(_ sender: Any) {
        dismiss(animated: true)
    }
    @IBOutlet weak var navigationBar: UINavigationBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.my_setNavigationBar()
       
        
        
        setSegmentedControl()
        if CheckInternet.Connection() {
            performSelector(inBackground: #selector(parseFeed), with: nil)
        } else {
             setAlertController(title: "No Internet Connection", message: "We could not load any news articles because you are not connected to the Internet.", preferredStyle: .alert, actionTitle: "OK")
        }
        newsTableView.delegate = self
        newsTableView.dataSource = self 

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        if newsTableView.indexPathForSelectedRow != nil {
          newsTableView.deselectRow(at: newsTableView.indexPathForSelectedRow!, animated: true)
        }
       
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if current.count == 0 {
            indicator.bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
            indicator.center = self.view.center
            indicator.color = UIColor.black
            indicator.startAnimating()
            indicator.alpha = 1
            view.addSubview(indicator)
            view.bringSubviewToFront(indicator)
        }
        
        segmentioView.valueDidChange = { segmentio, segmentIndex in
            switch segmentIndex {
                
            case 0:
              self.current = self.articles
            case 1:
                self.current = self.groupDictionary["NEWS"] ?? []
            case 2:
                  self.current = self.groupDictionary["OPINION"] ?? []
            case 3:
                  self.current = self.groupDictionary["FEATURES"] ?? []
            case 4:
                  self.current = self.groupDictionary["SHOWCASE"] ?? []
            case 5:
                  self.current = self.groupDictionary["SPORTS"] ?? []
            case 6:
                  self.current = self.groupDictionary["A&E"] ?? []
            case 7:
                  self.current = self.groupDictionary["THE PAW PRINT"] ?? []
            default:
                print("more coming")
            }
            self.newsTableView.reloadData()
        }
    }
    
    
    
    func setSegmentedControl() {
        
        let position = SegmentioPosition.dynamic
        let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white)
        let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none)
        let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0))
        segmentioView.selectedSegmentioIndex = 0
        let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: (
            defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)),
            selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white),
            highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white)
            )
            ,animationDuration: 0.2)
        
        let allItem = SegmentioItem(title: "ALL", image: nil)
        let aeItem = SegmentioItem(title: "A&E", image: nil)
        let featuresItem = SegmentioItem(title: "FEATURES", image: nil)
        let opinionItem = SegmentioItem(title: "OPINION", image: nil)
        let pawPrintItem = SegmentioItem(title: "PAW PRINT", image: nil)
        let sportsItem = SegmentioItem(title: "SPORTS", image: nil)
        let newsItem = SegmentioItem(title: "NEWS", image: nil)
        let showcaseItem = SegmentioItem(title: "SHOWCASE", image: nil)
        content = [allItem, newsItem, opinionItem, featuresItem, showcaseItem, sportsItem, aeItem, pawPrintItem]
        segmentioView.setup(content: content, style: .onlyLabel, options: options)
        
    }
    
    func setAlertController(title: String, message: String?, preferredStyle: UIAlertController.Style, actionTitle: String) {
        let ac = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
        ac.addAction(UIAlertAction(title: actionTitle, style: .default, handler: nil))
       present(ac, animated: true)
    }

    
    func loadThumbnail(url: URL) -> UIImage? {
   
        if let data = try? Data(contentsOf: url) {
            if let image = UIImage(data: data) {
            return image
            
        } else {
                return nil
            }
        } else {
            return nil
        }
    }
    
    
    
    
    @objc func parseFeed() {
        if let xmlContent = try? String(contentsOf: URL(string: "https://portolapilot.com/feed/")!) {
            let xml = try! XML.parse(xmlContent)
            let itemArray = xml["rss"]["channel"]["item"].all!
            
            for i in 0...itemArray.count - 1 {
                let item = itemArray[i]
                //configure categories array
               var categories = [String?]()
                for elements in item.childElements {
                    if elements.name == "category" {
                        categories.append(elements.text)
                    }
                }
                if categories.count < 3 {
                    for _ in 0...(2 - categories.count) {
                        categories.append(nil)
                    }
                }
                let object = xml["rss"]["channel"]["item"][i]
                let article = NewsArticle()
                article.title = object["title"].text ?? "News Article"
                article.link = object["link"].text ?? "https://portolapilot.com/"
                let formatter = DateFormatter()
                formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
                formatter.timeZone = Calendar.current.timeZone
                formatter.locale = Calendar.current.locale
                let dateString = object["pubDate"].text
                if dateString != nil {
                    article.pubDate = formatter.date(from: dateString!)!
                } else {
                    article.pubDate = Date.distantPast
                }
                if let rawAuthor = object["dc:creator"].text {
                    if rawAuthor.contains(",") {
                        let newAuthor = rawAuthor.split(separator: ",")
                        article.author = String(newAuthor[0])
                    }
                } else {
                    article.author = "Student Journalist"
                }
                
                article.category1 = categories[0]!
                article.category2 = categories[1]
                article.category3 = categories[2]
                article.content = object["content:encoded"].text ?? "Error Loading Article."
                if let linkString = object["link"].text {
                    let array = linkString.components(separatedBy: "/")
                        if array.count >= 5 {
                        let shortTitle = array[3]
                            if let data = try? String(contentsOf: URL(string: "http://portolapilot.com/wp-json/oembed/1.0/embed?url=http%3A%2F%2Fportolapilot.com%2F\(shortTitle)%2F")!) {
                                if let jsonData = JSON(parseJSON: data).dictionaryObject!["thumbnail_url"] as? String {
                                    if let urlImage = URL(string: jsonData) {
                                        article.imageLink = urlImage
                                    }
                                }
                            }
                    }
                }
                articles.append(article)
                
            }
            
           generateTypes()
            
        } else {
            setAlertController(title: "Error", message: "There was an error accessing Portola Pilot feed, please try again later.", preferredStyle: .alert, actionTitle: "OK")
        }
       
    }

    func generateTypes() {
        for news in articles {
            
                
                let key = news.category1
                let key2 = news.category2
                let key3 = news.category3
                
               
                let upper = key.uppercased()
                let upper2 = key2?.uppercased()
                let upper3 = key3?.uppercased()
                
                if var newsType = groupDictionary[upper] {
                   newsType.append(news)
                    groupDictionary[upper] = newsType
                } else {
                    
                    groupDictionary[upper] = [news]
                }
            if upper2 != nil {
                if var newsType2 = groupDictionary[upper2!] {
                    newsType2.append(news)
                    groupDictionary[upper] = newsType2
                } else {
                    
                    groupDictionary[upper2!] = [news]
                }
            }
            
            if upper3 != nil {
                if var newsType3 = groupDictionary[upper3!] {
                    newsType3.append(news)
                    groupDictionary[upper] = newsType3
                } else {
                    groupDictionary[upper3!] = [news]

                }
            }
            
            

            
    }
        groupCategories = [String](groupDictionary.keys)
        print(groupCategories)
        DispatchQueue.main.async {
            self.indicator.viewFadeOut()
            self.current = self.articles
            self.newsTableView.reloadData()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       
    }
 

}
