
convert_state <- function(df, format){

    stateconversion <- read_csv("data/stateconversion.csv")

    if(format %in% c("name","Name","NAME","long","Long","LONG","full","Full","FULL")){

        tojoin <- select(stateconversion, NAME, ABBREV)

        out <- df %>% 
            left_join(tojoin, by=c("STATE"="ABBREV"))

        return(out)
    } else if(format %in% c("abbrev","Abbrev","ABBREV","short","Short","SHORT")){
        tojoin <- select(stateconversion, NAME, ABBREV)

        out <- df %>% 
            left_join(tojoin, by=c("STATE"="NAME"))

        # Clean up weird ones: 
        out <- out %>% 
            mutate(ABBREV=case_when(
                STATE=="United States"~"US",
                STATE=="All"~"US",
                STATE=="Overall"~"US",
                STATE=="District of Columbia"~"DC",
                STATE=="Washington, DC"~"DC",
                TRUE~ABBREV
                ))

        return(out)
    } else if(format %in% c("hhs","Hhs","HHS")){

        statelen <- as.numeric(names(sort(table(unlist(lapply(df$STATE,nchar))),decreasing=TRUE)[1]))

        if(mean(statelen)==2){

            tojoin <- select(stateconversion, ABBREV, HHS)

            out <- df %>% 
                left_join(tojoin, by=c("STATE"="ABBREV"))

        } else {
            tojoin <- select(stateconversion, NAME, HHS)

            out <- df %>% 
                left_join(tojoin, by=c("STATE"="NAME"))

            # Clean up weird ones 
            out <- out %>% 
            mutate(HHS=case_when(
                STATE=="United States"~0,
                STATE=="All"~0,
                STATE=="Overall"~0,
                STATE=="District of Columbia"~3,
                STATE=="Washington, DC"~3,
                TRUE~HHS
                ))

        }

    } else {
        stop("Format not recognized")
    }

    return(out)

}
